Skip to main content

Looping over elements

Note☆ Learning Objectives
  • Visit the elements of a list using a loop
  • Visit the elements of paired lists

Looping through a list involves visiting each item in the list one by one to perform an operation on it. The for loop is the ideal tool to repeat a statement while iterating over whatever is in the list. There are multiple ways of doing the same thing!

Single Lists

Loop by element

NoteBASIC SYNTAX

for item in my_list:
    print(item)
  • This visits each item in the list and prints it.

Example

The following way traverses each letter one by one.

my_list = ['a','b','c','d','e','f']
for item in my_list:
    print(item)
a
b
c
d
e
f

Loop using range()

If accessing the elements by index is important in a problem you’re solving. You can iterate over all the indices of the list and using the [] accessors. Although not the “pythonic” way, this looping strategy can be very useful to compare an element to its neighbours.

NoteBASIC SYNTAX
for i in range(len(my_list)):

    print(i, my_list[i])

Example

measurements = [0.1, 0.5, 0.3, 0.5, 0.3]

for i in range(len(measurements)):

    print(i, measurements[i])
0 0.1
1 0.5
2 0.3
3 0.5
4 0.3

Loop using enumerate()

If there is a need to keep track of the iteration number i of each element, Python offers the built-in function enumerate() to loop over both the index and the item without having to use range() and len().

NoteBASIC SYNTAX
for i, item in enumerate(my_list):
    print(i, item)

Example

student_list = ["Sara", "Lucia", "Devin", "Henri","Luca", "Maria"]

for i, student in enumerate(student_list):
    print(i, student)
0 Sara
1 Lucia
2 Devin
3 Henri
4 Luca
5 Maria

Paired lists

Consider the following two lists that represent various travel destinations and their associated ticket prices.

destinations = ["Tokyo","Muscat", "Cancun", "Paris"]
ticket_prices = [2769.00, 2680.00, 478.00, 1347.00]

What if we would like to display each destination and its ticket price as such:

Tokyo  2769.00$
Muscat 2680.00$
Cancun  478.00$
Paris  1347.00$

An initial strategy would be to iterate over both lists using a for loop iterating enumerate(), assuming that both lists will always have the same length, such as :

destinations = ["Tokyo","Muscat", "Cancun", "Paris"]
ticket_prices = [2769.00, 2680.00, 478.00, 1347.00]

for i, destination in enumerate(destinations):
    price = ticket_prices[i]
    print(f"{destination} {price}$")
Tokyo 2769.0$
Muscat 2680.0$
Cancun 478.0$
Paris 1347.0$

Looping with zip()

The zip() function returns a single combined “sequence” returning the pair of destination and its corresponding price :

destinations = ["Tokyo","Muscat", "Cancun", "Paris"]
ticket_prices = [2769.00, 2680.00, 478.00, 1347.00]

for price, destination in zip(ticket_prices, destinations):
    print(f"{destination} {price}$")
Tokyo 2769.0$
Muscat 2680.0$
Cancun 478.0$
Paris 1347.0$

Sidenote: You can actually “see” what the resulting of zipping is by converting it into a list and printing it:

zip_result = zip(ticket_prices, destinations)
print(list(zip_result))
[(2769.0, 'Tokyo'), (2680.0, 'Muscat'), (478.0, 'Cancun'), (1347.0, 'Paris')]

It’s a list of pairs of values!

You can also combine multiple lists using zip, but be careful to respect the order of the unpacked items:

destinations = ["Tokyo","Muscat", "Cancun", "Paris"]
ticket_prices = [2769.00, 2680.00, 478.00, 1347.00]
durations = [7, 8, 3, 5]

for price, destination, duration in zip(ticket_prices, destinations, durations):
    print(f"{destination} {price}$ {duration} days")
Tokyo 2769.0$ 7 days
Muscat 2680.0$ 8 days
Cancun 478.0$ 3 days
Paris 1347.0$ 5 days

Example