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
[]
.
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.
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.
# 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
countries
.i
, to represent the index numbers of the items of the list starting with index 0
(i=0
).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.i
, which represents the index numbers of the list by 1
(i = i + 1
).