How to loop through a list in Python?
To loop through a list in Python, use a for loop, while loop or list comprehensions.
loop through a for loop
To loop through a for loop, use the loop as shown below.
# loop through a for loop
myList = [1, 2, 3, 4, 5]
for n in myList:
print(n)
In this example, we loop through the for loop and print each element.
1
2
3
4
5
Loop through a list using while loop
An alternative is to use a while loop to loop through a list. It is necessary to increase the iterator by 1.
# loop through a while loop
myList = [1, 2, 3, 4, 5]
n = 0
while n < len(myList):
print(myList[n])
n = n + 1
In this example, we loop through the while loop until the counter n exceeds the length of the list.
The len() function is used to find the length of the list, that is the number of elements.
Each element is printed and then the counter is incremented by one.
1
2
3
4
5
Loop through a list using list comprehension
The most concise way to iterate through a list is by using list comprehensions.
# loop through a list using list comprehension
myList = [1, 2, 3, 4, 5]
[print(n) for n in myList]
In this example list comprehension is used to print each element of the list.
1
2
3
4
5