my_list = ['a','b','c','d','e','f']
for item in my_list:
print(item)a
b
c
d
e
f
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!
Example
The following way traverses each letter one by one.
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.
Example
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().
Example
Consider the following two lists that represent various travel destinations and their associated ticket prices.
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 :
Tokyo 2769.0$
Muscat 2680.0$
Cancun 478.0$
Paris 1347.0$
zip()The zip() function returns a single combined “sequence” returning the pair of destination and its corresponding price :
Tokyo 2769.0$
Muscat 2680.0$
Cancun 478.0$
Paris 1347.0$
You can also combine multiple lists using zip, but be careful to respect the order of the unpacked items:
Tokyo 2769.0$ 7 days
Muscat 2680.0$ 8 days
Cancun 478.0$ 3 days
Paris 1347.0$ 5 days
Example