How can we loop through a list using a for loop in Python?

Overview

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 [ ].

Example

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.

How can we loop through a list in Python?

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.

Syntax

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.

Code

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)

Explanation

  • Line 1: We create a list named countries.
  • Line 2: We use a for loop to create an expression, which will make x become each item present in the list.
  • Line 3: We print all the items of the list we created.

Free Resources