Python – Iterate over list with 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)
Run Code Copy
1__ initialize variable x, with a list of three strings
3__ write a for loop, where we iterate over the, enumerated x
3__enumerate(x)__ enumerate of x, gives us an iterator, to iterate over the index and item at a time
3__index, item__ we have access to index and item during each iteration
4__ with having access to both index and item, print them to output using print method

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.

Related Tutorials

Code copied to clipboard successfully 👍