How to access the index value in a 'for' loop?
Solution 1
Use the built-in function enumerate()
:
for idx, x in enumerate(xs):
print(idx, x)
It is non-pythonic to manually index via for i in range(len(xs)): x = xs[i]
or manually manage an additional state variable.
Check out PEP 279 for more.
Solution 2
Using a for loop, how do I access the loop index, from 1 to 5 in this case?
Use enumerate
to get the index with the element as you iterate:
for index, item in enumerate(items):
print(index, item)
And note that Python's indexes start at zero, so you would get 0 to 4 with the above. If you want the count, 1 to 5, do this:
count = 0 # in case items is empty and you need it after the loop
for count, item in enumerate(items, start=1):
print(count, item)
Unidiomatic control flow
What you are asking for is the Pythonic equivalent of the following, which is the algorithm most programmers of lower-level languages would use:
index = 0 # Python's indexing starts at zero for item in items: # Python's for loops are a "for each" loop print(index, item) index += 1
Or in languages that do not have a for-each loop:
index = 0 while index < len(items): print(index, items[index]) index += 1
or sometimes more commonly (but unidiomatically) found in Python:
for index in range(len(items)): print(index, items[index])
Use the Enumerate Function
Python's enumerate
function reduces the visual clutter by hiding the accounting for the indexes, and encapsulating the iterable into another iterable (an enumerate
object) that yields a two-item tuple of the index and the item that the original iterable would provide. That looks like this:
for index, item in enumerate(items, start=0): # default is zero
print(index, item)
This code sample is fairly well the canonical example of the difference between code that is idiomatic of Python and code that is not. Idiomatic code is sophisticated (but not complicated) Python, written in the way that it was intended to be used. Idiomatic code is expected by the designers of the language, which means that usually this code is not just more readable, but also more efficient.
Getting a count
Even if you don't need indexes as you go, but you need a count of the iterations (sometimes desirable) you can start with 1
and the final number will be your count.
count = 0 # in case items is empty for count, item in enumerate(items, start=1): # default is zero print(item)
print(‘there were {0} items printed’.format(count))
The count seems to be more what you intend to ask for (as opposed to index) when you said you wanted from 1 to 5.
Breaking it down - a step by step explanation
To break these examples down, say we have a list of items that we want to iterate over with an index:
items = ['a', 'b', 'c', 'd', 'e']
Now we pass this iterable to enumerate, creating an enumerate object:
enumerate_object = enumerate(items) # the enumerate object
We can pull the first item out of this iterable that we would get in a loop with the next
function:
iteration = next(enumerate_object) # first iteration from enumerate
print(iteration)
And we see we get a tuple of 0
, the first index, and 'a'
, the first item:
(0, 'a')
we can use what is referred to as "sequence unpacking" to extract the elements from this two-tuple:
index, item = iteration
# 0, 'a' = (0, 'a') # essentially this.
and when we inspect index
, we find it refers to the first index, 0, and item
refers to the first item, 'a'
.
>>> print(index)
0
>>> print(item)
a
Conclusion
- Python indexes start at zero
- To get these indexes from an iterable as you iterate over it, use the enumerate function
- Using enumerate in the idiomatic way (along with tuple unpacking) creates code that is more readable and maintainable:
So do this:
for index, item in enumerate(items, start=0): # Python indexes start at zero
print(index, item)
Solution 3
It's pretty simple to start it from 1
other than 0
:
for index, item in enumerate(iterable, start=1): print index, item # Used to print in python<3.x print(index, item) # Migrate to print() after 3.x+
Solution 4
Tested on Python 3.12
Here are twelve examples of how you can access the indices with their corresponding array's elements using for loops, while loops and some looping functions. Note that array indices always start from zero by default (see example 4
to change this).
1. Looping elements with counter and +=
operator.
items = [8, 23, 45, 12, 78] counter = 0
for value in items: print(counter, value) counter += 1
Result:
0 8
1 23
2 45
3 12
4 78
2. Iterating elements using enumerate()
built-in function.
items = [8, 23, 45, 12, 78]
for i in enumerate(items): print(“index/value”, i)
Result:
index/value (0, 8)
index/value (1, 23)
index/value (2, 45)
index/value (3, 12)
index/value (4, 78)
3. Getting list's element and its index separately.
items = [8, 23, 45, 12, 78]
for index, value in enumerate(items): print(“index”, index, “for value”, value)
Result:
index 0 for value 8
index 1 for value 23
index 2 for value 45
index 3 for value 12
index 4 for value 78
4. You can change the index
value to any increment.
items = [8, 23, 45, 12, 78]
for i, item in enumerate(items, start=100): print(i, item)
Result:
100 8
101 23
102 45
103 12
104 78
5. Automatic counter incrementation with range(len(...))
methods.
items = [8, 23, 45, 12, 78]
for i in range(len(items)): print(“Index:”, i, “Value:”, items[i])
Result:
(‘Index:’, 0, ‘Value:’, 8)
(‘Index:’, 1, ‘Value:’, 23)
(‘Index:’, 2, ‘Value:’, 45)
(‘Index:’, 3, ‘Value:’, 12)
(‘Index:’, 4, ‘Value:’, 78)
6. Using for
loop inside function.
items = [8, 23, 45, 12, 78]
def enum(items, start=0): counter = start
for value in items: print(counter, value) counter += 1
enum(items)
Result:
0 8
1 23
2 45
3 12
4 78
7. Of course, we can't forget about while
loop.
items = [8, 23, 45, 12, 78] counter = 0
while counter < len(items): print(counter, items[counter]) counter += 1
Result:
0 8
1 23
2 45
3 12
4 78
8. yield
statement returning a generator object.
def createGenerator(): items = [8, 23, 45, 12, 78]
for (j, k) in enumerate(items): yield (j, k)
generator = createGenerator()
for i in generator: print(i)
Result:
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)
9. Inline expression with for
loop and lambda
.
items = [8, 23, 45, 12, 78]
xerox = lambda upperBound: [(i, items[i]) for i in range(0, upperBound)] print(xerox(5))
Result:
[(0, 8), (1, 23), (2, 45), (3, 12), (4, 78)]
10. Iterate over two lists at once using Python's zip()
function.
items = [8, 23, 45, 12, 78] indices = []
for index in range(len(items)): indices.append(index)
for item, index in zip(items, indices): print(”{}: {}“.format(index, item))
Result:
0: 8
1: 23
2: 45
3: 12
4: 78
11. Loop over 2 lists with a while
loop and iter()
& next()
methods.
items = [8, 23, 45, 12, 78] indices = range(len(items))
iterator1 = iter(indices) iterator2 = iter(items)
try: while True: i = next(iterator1) element = next(iterator2) print(i, element) except StopIteration: pass
Result:
0 8
1 23
2 45
3 12
4 78
12. Also, it's nice to iterate list's elements inside class' Static Method
.
items = [8, 23, 45, 12, 78]
class ElementPlus: @staticmethod # decorator def indexForEachOfMy(iterable): for pair in enumerate(iterable): print pair
ElementPlus.indexForEachOfMy(items)
Result:
(0, 8)
(1, 23)
(2, 45)
(3, 12)
(4, 78)
Solution 5
for i in range(len(ints)):
print(i, ints[i]) # print updated to print() in Python 3.x+