3.7.2. Looping using for#

We learned to use while to repeat a code block as long as a condition is true. Whereas the while statement is very powerful and sufficient for any looping, it is sometimes clearer to use the for statement instead.

The for statement means: “repeat this code block for each element of this variable”.

This means that we can easily iterate through each element of a list:

for variable_name in the_list:
    instruction1()
    instruction2()
    instruction3()
    etc.

For example:

a_list = [0, 1, 2, 'three', 'four']

for item in a_list:
    print("The current item is:", item)

print("done.")
The current item is: 0
The current item is: 1
The current item is: 2
The current item is: three
The current item is: four
done.