Learn the Python for Loop

Photo of Python computer code.

Learn the Python for loop. We cover the syntax, some of its inner workings, and useful auxiliary functions.

The for loop is a fundamental control structure in all languages. Python is no exception.

In our code we often keep structured data in collections. Python has first-class support for lists and dictionaries built into the language. We start with a list of cities:

cities = ["Canberra", "London", "Berlin", "Rome"]
for city in cities:
    print(city)

# Output:
# Canberra
# London
# Berlin
# Rome

Each individual string in the list is looped over. At each iteration city, the variable name between for and in, references the individual item in the collection.

Sometimes we may want to loop a fixed number of times. For this we can use the range() function. To loop 5 times:

for i in range(5):
    print(f"Loop number {i}")

# Output:
# Loop number 0
# Loop number 1
# Loop number 2
# Loop number 3
# Loop number 4

Range begins with 0. Sometimes we want access to the index of an item. We can use the enumerate function.

for i, city in enumerate(cities):
    print(f"City #{i+1} is {city}")

# City #1 is Canberra
# City #2 is London
# City #3 is Berlin
# City #4 is Rome

We can also use zip to combine two lists as pairs of items in one iteration.

countries = ["Australia", "UK", "Germany", "Italy"]
for city, country in zip(cities, countries):
    print(f"{city} is the capital of {country}")

# Output:
# Canberra is the capital of Australia
# London is the capital of UK
# Berlin is the capital of Germany
# Rome is the capital of Italy

Dictionaries are a little more complicated because they include both a key and value. We see below what enumerate() and zip() actually produce when used.

list(zip(cities, countries))
# [('Canberra', 'Australia'), ('London', 'UK'), ('Berlin', 'Germany'), ('Rome', 'Italy')]
list(enumerate(cities))
# [(0, 'Canberra'), (1, 'London'), (2, 'Berlin'), (3, 'Rome')]

These functions create tuple pairs: with zip() we get a pair of individual items, one from each list; with enumerate() we get a pair, the index with the item itself. These can be fed to the dict() function to generate dictionaries.

Note that we can use the output of zip() and enumerate() without converting to a list. To understand why requires a discussion on iterators. We convert to a list only to have the Python interpreter print all data that we generate.

capital_cities = dict(zip(cities, countries))
print(capital_cities)

# Output
# {'Canberra': 'Australia', 'London': 'UK', 'Berlin': 'Germany', 'Rome': 'Italy'}

Dictionaries are a little different. You can iterate over the keys, values, or both.

for key in capital_cities:
    print(f"{key} is a city.")

# Output:
# Canberra is a city.
# London is a city.
# Berlin is a city.
# Rome is a city.

for value in capital_cities.values():
    print(f"{value} is a country.")

# Output:
# Australia is a country.
# UK is a country.
# Germany is a country.
# Italy is a country.

for key, value in capital_cities.items():
    print(f"{key} is the capital city of {value}.")

# Output
# Canberra is the capital city of Australia.
# London is the capital city of UK.
# Berlin is the capital city of Germany.
# Rome is the capital city of Italy.

Note that the line for key in capital_cities: is equivalent to for key in capital_cities.keys(). By default a dictionary will iterate over its keys.