How can we loop through a list using while loop in Python

Overview

In Python, a list is a data structure that is a changeable/mutable and ordered sequence of elements. Each element or value present in a list is called an item.

In a Python program, lists are defined by having values between square brackets [].

Example

countries = ["USA", "CHINA", "TURKEY"]

From the example given above, countries is a list variable, while USA, CHINA and TURKEY are all elements of the list.

How can we loop through a list in Python

To loop through a list in Python means repeating something over and over the items of a list, until a particular condition is satisfied.

We can loop through a list using a while loop. Here, we use the len() function. The len() function is used to determine the length of the list we created. This function starts the iteration at the 0 index, going through all the items of the list by referring to their indexes.

Code example

# creating a list
countries = ["USA", "CHINA", "BRAZIL", "TURKEY"]
# starting at 0 index
i = 0
# using a while loop
while i < len(countries):
print(countries[i])
# giving an incrememt of 1 to i
i = i + 1

Code explanation

  • Line 2: We create a list named countries.
  • Line 5: We create a variable i, to represent the index numbers of the items of the list starting with index 0 (i=0).
  • Line 8: We create a while loop and use the len() function to iterate over the list by referring to all the index numbers of each items of the list.
  • Line 9: We print the elements of the list.
  • Line 12: We increment i, which represents the index numbers of the list by 1 (i = i + 1).

Free Resources