How to Use a For Loop to Iterate over a List

Created with Sketch.

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

Code language: Python (python)

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)

Code language: Python (python)

Output:

New York
Beijing
Cairo
Mumbai
Mexico

Code language: Shell Session (shell)

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)

Code language: Python (python)

Output:

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

Code language: Shell Session (shell)

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}")

Code language: Python (python)

Output:

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

Code language: Shell Session (shell)

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}")

Code language: Python (python)

Output:

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

Code language: Shell Session (shell)

Summary

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

Leave a Reply

Your email address will not be published. Required fields are marked *