How to Use a For Loop to Iterate over a List

Summary: in this tutorial, you’ll learn how to use the Python for loop to iterate over a list in Python.

Using Python for loop to iterate over a list #

To iterate over a list, you use the for loop statement as follows:

for item in list:
    # process the item

In this syntax, the for loop statement assigns an individual element of the list to the item variable in each iteration.

Inside the body of the loop, you can manipulate each list element individually.

For example, the following defines a list of cities and uses a for loop to iterate over the list:

cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']

for city in cities:
    print(city)

Try it

Output:

New York
Beijing
Cairo
Mumbai
Mexico

In this example, the for loop assigns an individual element of the cities list to the city variable and prints out the city in each iteration.

Using Python for loop to iterate over a list with index #

Sometimes, you may want to access indexes of elements inside the loop. In these cases, you can use the enumerate() function.

The enumerate() function returns a tuple that contains the current index and element of the list.

The following example defines a list of cities and uses a for loop with the enumerate() function to iterate over the list:

cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']

for item in enumerate(cities):
    print(item)

Try it

Output:

(0, 'New York')
(1, 'Beijing')
(2, 'Cairo')
(3, 'Mumbai')
(4, 'Mexico')

To access the index, you can unpack the tuple within the for loop statement like this:

cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']

for index, city in enumerate(cities):
    print(f"{index}: {city}")

Try it

Output:

0: New York
1: Beijing
2: Cairo
3: Mumbai
4: Mexico

The enumerate() function allows you to specify the starting index which defaults to zero.

The following example uses the enumerate() function with the index that starts from one:

cities = ['New York', 'Beijing', 'Cairo', 'Mumbai', 'Mexico']

for index, city in enumerate(cities,1):
    print(f"{index}: {city}")

Try it

Output:

1: New York
2: Beijing
3: Cairo
4: Mumbai
5: Mexico

Summary #

  • Use a for loop to iterate over a list.
  • Use a for loop with the enumerate() function to access indexes.

Quiz #

Quiz

Looping Over a List

4 questions

To help you understand how to use the Python for loop to iterate over a list effectively.

Was this helpful?