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 listcountries = ["USA", "CHINA", "BRAZIL", "TURKEY"]# starting at 0 indexi = 0# using a while loopwhile i < len(countries):print(countries[i])# giving an incrememt of 1 to ii = 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 index0(i=0). - Line 8: We create a
whileloop and use thelen()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 by1(i = i + 1).