A list
in Python is a data structure that is a changeable or mutable 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, we can see that countries
is a list variable, while "USA"
, "CHINA"
, and "TURKEY"
are all elements of the list.
To loop through a list in Python simply means to repeat something over and over in the items of a list, until a particular condition is satisfied.
We can loop through a list in Python using a for
loop.
For (expression):
statement(s)
The expression
given in the code above is usually a condition, and this statement
will execute when the condition is true.
In the code given below, we want to print all the items in the list one by one:
countries = ["USA", "CHINA", "TURKEY"]for x in countries:print(x)
countries
.for
loop to create an expression, which will make x
become each item present in the list.