Iterate over list using index
Iterate over list with index
To iterate over items of list with access to index also, use enumerate() builtin function. Pass the list as argument to enumerate() function, and we get access to both the index and item during iteration with the for loop.
The syntax of the For Loop to iterate over list x
with access to index of items is
for index, item in enumerate(x):
#code
Examples
1. Iterate over list x with index
In the following program, we take a list x
, iterate over the items with access to index.
Python Program
x = ['apple', 'banana', 'cherry']
for index, item in enumerate(x):
print(index, '-', item)
Output
0 - apple
1 - banana
2 - cherry
Summary
In this tutorial of Python Examples, we learned how to iterate over the items of a list with access to index as well using enumerate() function, with the help of well detailed examples.