A list in Python is a data structure that consists of a changeable or mutable ordered sequence of elements. Each element or value present in the list is called an item. In Python, lists are defined by putting their items between square brackets [ ]
.
countries = ["USA", "CHINA", "TURKEY"]
In the example above, countries
is a list variable, while "USA"
, "CHINA"
and "TURKEY"
are all items of the list.
To loop through a list in Python simply means repeating something over and over in the list until a particular condition is satisfied.
We can loop through a list in Python by referring to the index numbers of the elements of the list. In this case, all we need are the range()
and len()
functions to create a suitable iterable.
range()
functionThe range()
function in Python is used to iterate over a sequence type such as a list, a string, etc., with for
and while
loops.
range(start, stop[, step])
len()
functionThe len()
function returns the length of a list, string, dictionary, or any other iterable data format in Python. In simpler terms, we use the len()
function to determine the length of the list we created.
len(iterable_object)
range(len(iterable))
functionThe combination of the range()
and len()
functions, (range(len(iterable)
, is used to iterate over a list in Python. Using the two functions together, we can refer to the index numbers of all items or elements in a list.
In the example below, we will print all the items or elements of the list by simply referring to their index numbers.
# creating a listcountries = ["USA", "CHINA", "BRAZIL", "TURKEY"]# referring to their index numbers using the range(len(iterable))for i in range(len(countries)):print(countries[i])
countries
.for
loop and, using the range(len(iterable))
function, we refer to respective index numbers of all the items present in the list and create an iteration over all the items.The iterable we create in the code above is
[0, 1, 2, 3]
.