In this tutorial, you will learn how to iterate over a list using While loop statement, with the help of example programs.
Python List While Loop
To iterate over elements of a Python List using While loop statement, start with index of zero and increment the index till the last element of the list using length of the list. Inside the while block, we access the element of the list using list name and index.
Examples
In the following examples, While loop is used to iterate over the elements of a list. We cover examples where we iterate over the loops from starting to end of the list, and ending of the list to starting of the list.
1. Iterate over a list using While loop
In this example, we will take a Python List, and iterate over all the elements of this list using while loop.
Python Program
list_1 = [4, 52, 6, 9, 21]
index = 0
while index < len(list_1) :
print(list_1[index])
index += 1
Output
4
52
6
9
21
Reference tutorials for the above program
2. Iterate over a list in reverse using While loop
In this example, we will take a Python List, and iterate over all the elements from end to start of this list using while loop.
We have to start with an index of the last element in the last, and decrement this index in each iteration, till we reach the first element in the list.
Python Program
list_1 = [4, 52, 6, 9, 21]
index = len(list_1) - 1
while index >= 0 :
print(list_1[index])
index -= 1
Output
21
9
6
52
4
3. Iterate and update the list using While loop
If we are using a For loop, we cannot update the elements in the list. But, with a While loop, we can update the element.
In this example, we will take a list on numbers, iterate over all the elements and increment each element by 2.
Python Program
list_1 = [4, 52, 6, 9, 21]
#update list items
index = 0
while index < len(list_1) :
list_1[index] += 2
index += 1
#print list items
index = 0
while index < len(list_1) :
print(list_1[index])
index += 1
Output
6
54
8
11
23
Conclusion
In this Python Tutorial, we learned how to iterate over elements of a List using While Loop statement.