Python List – Iterate over Elements

To iterate over elements of a List there are many methods. Some of them are: using while loop, using for loop, etc.

In this tutorial, we will go through examples, where we shall take a list, and traverse through all elements of the list.

Example 1 – Iterate Over Python 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.

example.py – Python Program

aList = [2020, 'www.tutorialKart.com', True]

index = 0
while index<len(aList):
    print(aList[index])
    index = index+1
Try Online

Run the above Python program, and you will get the following output.

Output

2020
www.tutorialKart.com
True

We have accessed each of the element in list using index and while loop.

Example 2 – Iterate Over Python List using For Loop

In this example, we shall use for loop to iterate over Python List. We can traverse through a Python List using for loop as shown in the following Python program. During each iteration, we get to access the element.

example.py – Python Program

aList = [2020, 'www.tutorialKart.com', True]

for element in aList:
    print(element)
Try Online

Run the above Python program.

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.

Conclusion

In this Python Tutorial, we learned how to access or traverse through List elements.