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 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
- Python Program to Find Duplicate Items of a List
- How to Append List to Another List in Python? – list.extend(list)
- Python – Get Index or Position of Item in List
- Python Program to Find Largest Number in a List
- Python Program to Find Unique Items of a List
- Python – Check if Element is in List
- Python List with First N Elements
- Python Program to Find Smallest Number in List
- How to Get the list of all Python keywords?
- Python List of Lists