Looping over lists

Iterating over lists can be confusing. You can mistake looping over the list elements for list items. This simple notbooks aims at pointing the differences.

Let there be the following list:


In [ ]:
week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

The following for structure cycles over the elements of the list:


In [ ]:
for weekday in week:
    print("Today is ",weekday)

Alternatively we loop over the indices of the list:


In [ ]:
for i in range(len(week)):
    print("This is the value of the index, ", i)
    weekday = week[i] #once we have the index we can obtain the corresponding list element
    print("Today is ",weekday)

Third possibility, use enumerate to generate a sequence with pairs of indices and elements:


In [ ]:
for i, weekday in enumerate(week):
    print("This is the index ",i)
    print("This is the element ",weekday)

Iterating over elements is more general than iterating based on indices. The reason is that several collections do not have a predefined order and cannot be accessed via indices. As a simple example, if we convert the previous list into a set, we can still iterate over its elements, but we cannot loop over the indices.


In [ ]:
week_set = set(week)

In [ ]:
for weekday in week_set: #Remark that order is arbitrary!
    print("Today is ",weekday)

In [ ]:
#Try this and read the error:

for i in range(len(week_set)):
    print("This is the value of the index, ", i)
    weekday = week_set[i] 
    print("Today is ",weekday)

In [ ]: