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
"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
len() functions to create a suitable iterable.
range() function in Python is used to iterate over a sequence type such as a list, a string, etc., with
range(start, stop[, step])
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.
The combination of the
(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 list countries = ["USA", "CHINA", "BRAZIL", "TURKEY"] # referring to their index numbers using the range(len(iterable)) for i in range(len(countries)): print(countries[i])
forloop 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].
View all Courses