Python List While Loop
Python List is a collection of items. While loop can be used to execute a set of statements for each of the element in the list.
In this tutorial, we will learn how to use while loop to traverse through the elements of a given list.
Syntax – List While Loop
Elements of list are ordered. So, we can access the elements using index. We will make use of this property to traverse through items of list using while loop.
In general, the syntax to iterate over a list using while loop is
index = 0 while index < len(myList): element = myList[index] #statement(s) index += 1
- element contains value of the this element in the list. For each iteration, next element in the list is loaded into this variable with the changing index.
- myList is the Python List over which we would like to traverse through.
- statement(s) are block are set of statement(s) which execute for each of the element in the list.
Example 1: Python List While Loop
In this example, we will take a list of strings, and iterate over each string using while loop, and print the string length.
myList = ['pineapple', 'banana', 'watermelon', 'mango'] index = 0 while index < len(myList): element = myList[index] print(len(element)) index += 1
9 6 10 5
Example 2: Python List While Loop- Over List of Numbers
In this example, we will take a list of numbers, and iterate over each number using while loop, and in the body of while loop, we will check if the number is even or odd.
myList = [5, 7, 8, 3, 4, 2, 9] index = 0 while index < len(myList): element = myList[index] if element % 2 == 0: print('even') else: print('odd') index += 1
odd odd even odd even even odd
In this tutorial of Python Examples, we learned how to use While Loop to iterate over Python List elements.