In this article, we will show how to write a Python program to iterate or traverse over a list of elements with examples. There are multiple options to iterate over the elements or items in a list, including the for loop, range, while loop, enumerate, list comprehension, lambda, map, and chain function. You can use any of the below methods based on your requirements.
Python Program to Iterate Over a List Using a For Loop
The for loop is the most popular and best approach to iterate over a list of elements. In the program below, we have declared an integer list of six elements. Next, the door loop will iterate over num list and print the values in it. Here, val is the actual value of the num list element.
num = [5, 10, 15, 20, 25, 30]
for val in num:
print(val)
5
10
15
20
25
30
Using a for loop with range
You can also use the range() function along with the for loop to iterate the list index positions. From the example below, the len() will find and return the total items. Next, the range() function accepts start, stop, and step args. It means the for loop will iterate the list index from 0 to n (len() -1). We have used the index position to access the list item.
num = [10, 20, 30, 40, 50]
for i in range(len(num)):
print(num[i])
Using enumerate
The enumerate function is very helpful in iterating the list items and accessing the index position along with the actual element. In the below. Program, i is the index position, and val is the list element present at that position.
num = [10, 20, 30, 40, 50]
for i, val in enumerate(num):
print(i, "Position =", val)
0 Position = 10
1 Position = 20
2 Position = 30
3 Position = 40
4 Position = 50
Python Program to Iterate Over a List Using a While Loop
This program uses a while loop instead of a For loop to iterate the integer list item and prints the elements. Don’t forget to increment the i value.
num = [5, 10, 15, 20, 25, 30]
i = 0
while i < len(num):
print(num[i])
i = i + 1
5
10
15
20
25
30
Using List Comprehension
On par with the first example, list comprehension is the best approach to iterate over the elements in a list. It internally uses the for loop to iterate the list item, but it provides the shortest and most readable syntax.
num = [10, 20, 30, 40, 50]
[print(val) for val in num]
10
20
30
40
50
Python Program to Iterate Over a List Using lambda and map
Here, lambda a:a means it accepts every element in a list iterable and returns the same. The list function converts the map object.
num = [10, 20, 30, 40, 50]
res = list(map(lambda a:a, num))
print(res)
[10, 20, 30, 40, 50]
Using itertools
The itertools module has the chain function that can be helpful to traverse over list items. If you use the cycle() function (itertools.cycle(num)), it will enter the infinity loop and print the below five records an infinite number of times.
import itertools
num = [10, 20, 90, 40, 50]
for val in itertools.chain(num):
print(val)
10
20
90
40
50