Loops (Good)

What to expect in this chapter

In this chapter, I will show you how to exercise more control over what happens in loops by using the continue and break statements. I will also introduce you to list comprehension, a super-optimised variant of the for a loop. You can use this to create list from other lists.

1 Interrupting the flow

There are many instances when you want to change the flow of a loop from within. The two commands, break and continue, allow us to do just that. Let me show you some examples of how to use them.

  1. for power in range(5):
        number = 10**power
        if number > 5000:
            break
        print(power, number)

    We use break to break-out of the loop and terminate it.
    We typically use it with if so that we break out if a certain condition is met.
    This will also work with a while loop.

    0 1
    1 10
    2 100
    3 1000
  2. for power in range(5):
        if power == 3:
            continue        # Don't proceed further
                            # IN THE CURRENT LOOP
                            # if i == 3
        number = 10**power
        print(power, number)

    Sometimes we want to skip an iteration and just move on to the next. continue allows us to do this by skipping everything after it.
    Notice how there is no printout for power = 3.
    continue too is typically used with if.
    This will also work with a while loop.

    0 1
    1 10
    2 100
    4 10000
  3. for number in range(10):
        # Don't proceed if the remainder is zero
        # I.e. if the number is even
        if number % 2 == 0:
            continue
        print(number)
    1
    3
    5
    7
    9
  4. number=0
    
    while True:
        print(number)
        number += 1
        if number > 4: break

    Let me redo the while example from the past chapter using break.
    Notice that I setup the loop to run forever1 and use break to stop it.

    0
    1
    2
    3
    4
Remember

Remember you can use break and continue (with impunity) to interrupt the flow of loops.

2 List comprehension!

The exercises of the previous chapter had you using loops to create lists. However, creating new lists from other lists is so common that Python has an optimised syntax called list comprehension to do just that. Here is how it works.

2.1 Basic syntax

[number for number in range(5)]

The adjoining creates a simple list with numbers from 0 to 4.
The syntax is very similar to that of a for loop. You just need to put the thing you want as an output at the front.

[0, 1, 2, 3, 4]
[number**2 for number in range(5)]

If you want to create a list of squares, we just have to:

[0, 1, 4, 9, 16]

2.2 List comprehension with conditions

[number for number in range(10) if number % 2 ==0]

List comprehension has several useful features. One such allows us to specify a condition. Here is an example:

[0, 2, 4, 6, 8]

3 Other useful stuff

3.1 for with unpacking

Python allows a neat trick called unpacking, which works like this:

x, y, z=[1, 2, 3]
print(f'x = {x}, y = {y}, z = {z}')
x = 1, y = 2, z = 3

Unpacking can be put to good use (for example) when we are dealing with 2D list. We can combine unpacking with a for loop to extract elements as follows:

py_superhero_info = [['Natasha Romanoff', 'Black Widow'],
                     ['Tony Stark', 'Iron Man'],
                     ['Stephen Strange', 'Doctor Strange']]

for real_name, super_name in py_superhero_info:
    print(f"{real_name} is Marvel's {super_name}!")
Natasha Romanoff is Marvel's Black Widow!
Tony Stark is Marvel's Iron Man!
Stephen Strange is Marvel's Doctor Strange!

3.2 for with zip()

Let’s revisit the example from the previous chapter that had two lists of real and superhero names that we used to print. There is yet another way to solve this task using a function called zip(). zip() is a neat function that can do some cool things. For the moment let me show you how to use zip() to combine two lists.

super_names = ["Black Widow", "Iron Man", "Doctor Strange"]
real_names = ["Natasha Romanoff", "Tony Stark", "Stephen Strange"]

for real_name, super_name in zip(real_names,super_names):
    print(f"{real_name} is Marvel's {super_name}!")
Natasha Romanoff is Marvel's Black Widow!
Tony Stark is Marvel's Iron Man!
Stephen Strange is Marvel's Doctor Strange!

This is by far the most elegant solution we have for using multiple lists with a for loop.

3.3 for with dictionaries

You will invariably need to loop through dictionaries in your programming career. Here is how you can do it with a for loop.

superhero_info={"Natasha Romanoff": "Black Widow",
                "Tony Stark": "Iron Man",
                "Stephen Strange": "Doctor Strange"}

for key, value in superhero_info.items():
    print(f"{key} is Marvel's {value}!")
Natasha Romanoff is Marvel's Black Widow!
Tony Stark is Marvel's Iron Man!
Stephen Strange is Marvel's Doctor Strange!

The ‘hidden’ function items() spits out both the key and the corresponding value.

If you like, you can directly access the keys as follows:

for key in superhero_info.keys():
    value=superhero_info[key]
    print(f"{key} is Marvel's {value}!")
Natasha Romanoff is Marvel's Black Widow!
Tony Stark is Marvel's Iron Man!
Stephen Strange is Marvel's Doctor Strange!

By the way, I have used the variable names key and value to highlight their roles in the dictionary. You can use whatever you like. In fact, using real_name and super_name is preferred.

Back to top

Footnotes

  1. or the end of the Universe↩︎