Loops#

Often, code blocks need to be executed repeatedly. In notebooks, we just may execute a code cell at the desired times. But it’s better to use loops, also part of the control flow tools.

See also:

For loops#

For looping over a range of numbers, we can use a simple for loop and the range function. The range function helps to easily define the number of loop executions.

In the following cell, the print(i) command will be executed a couple of times for different values of i. We iterate over a range of values. Like for the if statement, the to-be executed code block needs to be intended. Also remember that the defined end in a range is not inclusive:

for i in range(0, 5):
    print(i)
0
1
2
3
4

You can also loop over a range of numbers with a defined step, for example, step 3:

for i in range(0, 10, 3):
    print(i)
0
3
6
9

Iterating over arrays allows you to do something with all array elements:

for animal in ["Dog", "Cat", "Mouse"]:
    print(animal)
Dog
Cat
Mouse

Using the built-in zip function, we can iterate over two arrays in parallel, pair-wise like this:

# going through arrays pair-wise
measurement_1 = [1, 9, 7, 1, 2, 8, 9, 2, 1, 7, 8]
measurement_2 = [4, 5, 5, 7, 4, 5, 4, 6, 6, 5, 4]

for m_1, m_2 in zip(measurement_1, measurement_2):
    print("Paired measurements: " + str(m_1) + " and " + str(m_2))
Paired measurements: 1 and 4
Paired measurements: 9 and 5
Paired measurements: 7 and 5
Paired measurements: 1 and 7
Paired measurements: 2 and 4
Paired measurements: 8 and 5
Paired measurements: 9 and 4
Paired measurements: 2 and 6
Paired measurements: 1 and 6
Paired measurements: 7 and 5
Paired measurements: 8 and 4

If we want to know the index of the element in the list as well, the built-in enumerate function comes in handy:

# numbering and iterating through collections
for index, animal in enumerate(["Dog", "Cat", "Mouse"]):
    print(f"The animal number {index} in the list is {animal}")
The animal number 0 in the list is Dog
The animal number 1 in the list is Cat
The animal number 2 in the list is Mouse

Generating lists in loops#

We can generate lists using for loops. The conventional way of doing this involves multiple lines of code:

# we start with an empty list
numbers = []

# and add elements
for i in range(0, 5):
    numbers.append(i * 2)
    
print(numbers)
[0, 2, 4, 6, 8]

One can also write that shorter. The underlying concept is called generators. This is also part of what the community calls “The Pythonic Way”—making use of available classes and concepts to write short, clean, and understandable code.

numbers = [i * 2 for i in range(0, 5)]

print(numbers)
[0, 2, 4, 6, 8]

The conventional combination involving an if-statement looks like this:

# we start with an empty list
numbers = []

# and add elements
for i in range(0, 5):
    # check if the number is odd
    if i % 2:
        numbers.append(i * 2)
    
print(numbers)
[2, 6]

And the “Pythonic Way” like this:

numbers = [i * 2 for i in range(0, 5) if i % 2]

print(numbers)
[2, 6]

While loops#

Another way of looping is using the while loop. It checks a condition before each iteration, similar to the if statement. It will interrupt execution as soon as the condition is no longer true:

number = 1024

while (number > 1):
    number = number / 2
    print(number)
512.0
256.0
128.0
64.0
32.0
16.0
8.0
4.0
2.0
1.0

Interrupting loops#

You can interrupt loops at specific points in your code using the break command:

for i in range(10):
    print(i)
    if i > 5:
        break
0
1
2
3
4
5
6
number = 1024

while (True):
    number = number / 2
    print(number)
    
    if number < 1:
        break
512.0
256.0
128.0
64.0
32.0
16.0
8.0
4.0
2.0
1.0
0.5

Skipping iterations in loops#

If you want to skip iterations, you can use the continue statement. That often makes sense in combination with an if:

for i in range(0, 10):
    if (i >= 3) and (i <= 6):
        continue
    print(i)
0
1
2
7
8
9

Exercise 1#

Assume you have a list of filenames, and you want to do something with them, for example, print them out. Program a for loop which prints out all file names that end with “tif”.

file_names = ['dataset1.tif', 'dataset2.tif', 'summary.csv', 'readme.md', 'blobs.tif']

Exercise 2#

Assume you have a list of circle radii. Make a table (dictionary) with two columns: radius and area.

radii = [3, 15, 67, 33, 12, 8, 12, 9, 22]