In this Python tutorial, how to iterate over elements in a list using looping statements like While loop, and For loop, with examples.
Python List – Iterate over Elements
You can use a For loop to iterate over elements of a list, or you can use a while loop with index starting at 0 and ending at length of list minus one.
Examples
In the following examples, we will use each of the looping statements, to traverse the elements in given list.
1. Iterate over list using While loop
In this example, we shall use while loop to iterate over Python List. We know that elements of Python List can be accessed using index. So, we shall take a variable index with initial value of 0
and then increment the index during each while loop iteration, until the length of the list.
Python Program
aList = [2020, 'www.tutorialKart.com', True]
index = 0
while index<len(aList):
print(aList[index])
index = index+1
Output
2020
www.tutorialKart.com
True
We have accessed each of the element in list using index and while loop.
Reference tutorials for the above program
2. Iterate over list using For loop
In this example, we shall use For loop to iterate over a list. We can traverse through a list using for loop as shown in the following Python program. During each iteration, we get to access the element.
Python Program
aList = [2020, 'www.tutorialKart.com', True]
for element in aList:
print(element)
Otuput
2020
www.tutorialKart.com
True
We have accessed each of the element in list using index and while loop. We used only a single print statement, as this is just an example to demonstrate how to use for loop to traverse through the list elements. But you may write as many statements as required.
Reference tutorials for the above program
Conclusion
In this Python Tutorial, we learned how to access or traverse through elements in a list.