# | include: false
import numpy as np
import pandas as pd
256852) np.random.seed(
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.
-
for power in range(5): = 10**power number if number > 5000: break print(power, number)
We use
break
to break-out of the loop and terminate it.
We typically use it withif
so that we break out if a certain condition is met.
This will also work with awhile
loop.0 1 1 10 2 100 3 1000
-
for power in range(5): if power == 3: continue # Don't proceed further # IN THE CURRENT LOOP # if i == 3 = 10**power number 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 forpower = 3
.continue
too is typically used withif
.
This will also work with awhile
loop.0 1 1 10 2 100 4 10000
-
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
-
=0 number while True: print(number) += 1 number if number > 4: break
Let me redo the
while
example from the past chapter usingbreak
.
Notice that I setup the loop to run forever1 and usebreak
to stop it.0 1 2 3 4
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
for number in range(5)] [number
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]
**2 for number in range(5)] [number
If you want to create a list of squares, we just have to:
[0, 1, 4, 9, 16]
2.2 List comprehension with conditions
for number in range(10) if number % 2 ==0] [number
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:
=[1, 2, 3]
x, y, zprint(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:
= [['Natasha Romanoff', 'Black Widow'],
py_superhero_info '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.
= ["Black Widow", "Iron Man", "Doctor Strange"]
super_names = ["Natasha Romanoff", "Tony Stark", "Stephen Strange"]
real_names
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.
={"Natasha Romanoff": "Black Widow",
superhero_info"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():
=superhero_info[key]
valueprint(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.
Footnotes
or the end of the Universe↩︎