list in Python 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 above, we can see that
countries is a list variable, while
"TURKEY" are all elements of that list.
To loop through a list in Python means to repeat something over and over the items of the list until a particular condition is satisfied.
We can use the list comprehension method to loop through a list because it offers the shortest syntax for looping through a list.
As previously mentioned, the list comprehension method offers a shorter syntax.
*expression* for *item* in *iterable* if *condition* == True
The list comprehension method is a shorthand for the use of the
for loop, which helps us print all the items of a particular list.
# creating a list countries = ["USA", "CHINA", "BRAZIL", "TURKEY"] # using the list comprehension method [print(x) for x in countries]
View all Courses