Python List - Loop through Items - For, While, Enumerate
Python - Loop through list
You can loop through a list in Python using While loop, or For loop. We will go through each of them and their variations with examples.
Examples
1. Loop through list using While loop
In the following example, we take a list my_list with three items. We have to iterate over this list using a Python While Loop.
Take a While loop with a counter i that increments in the loop over iterations from 0 up to length of the list. Inside the loop, we access the item in the list using the counter as index.
Python Program
my_list = ['apple', 'banana', 'cherry']
i = 0
while i < len(my_list):
print(my_list[i])
i += 1
Output
apple
banana
cherry
2. Loop through List using For loop
We can also use a Python For Loop to directly access the elements itself rather than the index, inside the loop.
Python Program
my_list = ['apple', 'banana', 'cherry']
for item in my_list:
print(item)
You can use this way, if you need access to the actual item itself rather than the index inside the For loop body.
3. Loop through List using index in For loop
Using Python For Loop with range, we can loop through the index and access the item in the list using this index.
Python Program
my_list = ['apple', 'banana', 'cherry']
for i in range(len(my_list)):
print(my_list[i])
You can use this way if you need access to the index during the iteration.
4. Loop through List using enumerate() to access both the element and index inside the For loop
With enumerate() function, you can access both index and the item inside a For loop body.
Python Program
my_list = ['apple', 'banana', 'cherry']
for index, item in enumerate(my_list):
print(f"mylist[{index}] = {item}")
Output
mylist[0] = apple
mylist[1] = banana
mylist[2] = cherry
Summary
In this tutorial of Python Examples, we learned how to iterate through a list, using looping statements, with the help of well detailed example programs.