Accessing the index in 'for' loops?

+1 vote

How do I access the index itself for a list like the following?

ints = [8, 23, 45, 12, 78]

When I loop through it using a for loop, how do I access the loop index, from 1 to 5 in this case?

Aug 28, 2018 in Python by bug_seeker
• 14,960 points
20 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
0 votes

Using an additional state variable, such as an index variable (which you would normally use in languages such as C or PHP), is considered non-pythonic.

The better option is to use the built-in function enumerate(), available in both Python 2 and 3:

for idx,val in enumerate(ints):
    print(idx, val)

answered Aug 28, 2018 by Priyaj
• 56,100 points

Related Questions In Python

0 votes
1 answer

Accessing the index in 'for' loops?

Use enumerate to get the index with ...READ MORE

answered Mar 12 in Python by Trisha
8 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,710 points
36 views
0 votes
1 answer

Get index in for loop

Use enumerate(): for index, value in enumerate(array): ...READ MORE

answered Apr 24, 2018 in Python by Nietzsche's daemon
• 4,260 points
13 views
0 votes
2 answers

Finding the index of a character in python string

You can use word.find('o') as well to ...READ MORE

answered Jun 1, 2018 in Python by george
• 200 points
47 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
19 views
+4 votes
6 answers
0 votes
1 answer

What is the flow control for “continue” in python?

This is the way "continue" statement works! You ...READ MORE

answered Jul 16, 2018 in Python by Priyaj
• 56,100 points
29 views
+1 vote
1 answer

What is the function for Factorial in Python

Easiest way: math.factorial(x) (available in 2.6 and ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 56,100 points

edited Aug 21, 2018 by Omkar 53 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.