How to loop through a list using the list comprehension method
Overview
A 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 [ ].
Example
countries = ["USA", "CHINA", "TURKEY"]
From the example above, we can see that countries is a list variable, while "USA", "CHINA", and "TURKEY" are all elements of that list.
How to loop through a list in Python
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.
The list comprehension method
As previously mentioned, the list comprehension method offers a shorter syntax.
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.
Code example
# creating a listcountries = ["USA", "CHINA", "BRAZIL", "TURKEY"]# using the list comprehension method[print(x) for x in countries]
Code explanation
- Line 2: We create a list and name it
countries. - Line 5: We use the list comprehension method to print all of the items of the list.