Text
stringlengths
1
9.41k
range(n) with a single integer argument will generate an arithmetic sequence from 0 up to, but not including, the value of the argument. Notice, though, that if we use range(n) our loop will execute n times. What if we wanted to iterate integers in the interval [5, 10]?
How would we do that? ----- ``` >>> for n in range(5, 11): ...
print(n) ... 5 6 7 8 9 10 ``` The syntax here, when we use two arguments, is range(<start>, ``` <stop>), where <start> and <stop> are integers or variables with inte ``` ger values.
The range will include integers starting at the start value up to but not including the stop value. What if, for some reason, we wanted only even or odd values?
Or what if we wanted to count by threes, or fives, or tens? Can we use a different step size or stride? Yes, of course. These are all valid arithmetic sequences.
Let’s count by threes. ``` >>> for n in range(3, 19, 3): ... print(n) ... 3 6 9 12 15 18 ``` This three argument syntax is range(<start>, <stop>, <stride>).
The last argument, called the stride or step size corresponds to the difference between terms in the arithmetic sequence (the default stride is 1). Can we go backward? Yup.
We just use a negative stride, and adjust the start and stop values accordingly. ``` >>> for n in range(18, 2, -3): ...
print(n) ... 18 15 12 9 6 3 ``` This yields a range which goes from 18, down to but not including 2, counting backward by threes. So you see, range() is pretty flexible. ----- ###### What if I just want to do something many times and I don’t care about the members in the sequence? No big deal.
While we do require a variable to hold each member of the sequence or other iterable we’re iterating over, we aren’t required to use it in the body of the loop.
There is a convention, not required by the language, but commonly used, to use an underscore as the name for a variable that we aren’t going to use or don’t really care about. ``` >>> for _ in range(5): ...
print("I don't like Brussles sprouts!") ... I don't like Brussles sprouts! I don't like Brussles sprouts! I don't like Brussles sprouts! I don't like Brussles sprouts! I don't like Brussles sprouts! ``` (Now you know how I feel about Brussels sprouts.) ###### Comprehension check 1.
What is the evaluation of sum(range(5))? 2. What is the evaluation of max(range(10))? 3.
What is the evaluation of len(range(0, 10, 2)) ###### 11.6 Iterables As we have seen, iterables are Python’s way of controlling a for loop. You can think of an iterable as a sequence or composite object (composed of many parts) which can return one element at a time, until the sequence is exhausted.
We usually refer to the elements of an iterable as _members of the iterable._ It’s much like dealing playing cards from a deck, and doing something (performing a task or calculation) once for each card that’s dealt. A deck of playing cards is an iterable.
It has 52 members (the individual cards). The cards have some order (they may be shuffled or not, but the cards in a deck are ordered nonetheless). We can deal cards one _at a time.
This is iterating through the deck.
Once we’ve dealt the 52nd_ card, the deck is exhausted, and iteration stops. Now, there are two ways we could use the cards. First, we can use the information that’s encoded in each card.
For example, we could say the name of the card, or we could add up the pips on each card, and so on. Alternatively, if we wanted to do something 52 times (like push-ups) we could do one push-up for every card that was dealt.
In this case, the information encoded in each card and the order of the individual cards would be irrelevant.
Nevertheless, if we did one push-up for every card that was dealt, we’d know when we reached the end of the deck that we’d done 52 push-ups. ----- So it is in Python.
When iterating some iterable, we can use the data or value of each member (say calculating the sum of numbers in a list), or we can just use iteration as a way of keeping count.
Both are OK in Python. ###### Using the data provided by an iterable Here are two examples of using the data of members of an iterable. First, assume we have a list of integers and we want to know how many of those numbers are even and how many are odd.
Say we have such a list in a variable named lst. ``` evens = 0 for n in lst: if n % 2 == 0: # it's even evens += 1 print(f"There are {evens} even numbers in this list, " f"and there are {len(lst) - evens} odd numbers.") ``` As another example, say we have a list of all known periodic comets, and...
We would iterate through the list of comets, check to see each comet’s orbital period, and if that value were less than 100 years, we’d append that comet to another list.
In the following example, the list COMETS contains tuples in which the first element of the tuple is the name of the comet, and the second element is its orbital period in years.[6] ``` """ Produce a list of Halley's type periodic comets with orbital period less than 100 years. """ COMETS = [('Mellish', 145),...
You get the idea. short_period_comets = [] for comet in COMETS: if comet[1] < 100: short_period_comets.append(comet) # Yes, there's a better way to do this, # but this suffices for illustration. ``` Here we’re using the data encoded in each member of the iterable, ``` COMETS. ``` 6The orb...
Accordingly, we’ve given the variable which holds the individual members returned by the iterable the name _. _ is commonly used as a name for a variable that we aren’t going to use in any calculation.
It’s the programmer’s way of saying, “Yeah, whatever, doesn’t matter what value it has and I don’t care.” So these are two different ways to treat an iterable.
In one case, we care about the value of each member of the iterable; in the other, we don’t.
However, both approaches are used to govern a for loop. ###### 11.7 Iterating over strings We’ve seen how we can iterate over sequences such as lists, tuples, and ranges.
Python allows us to iterate over strings the same way we do for other sequences! When we iterate over a string, the iterator returns one character at a time.
Here’s an example: ``` >>> word = "cat" >>> for letter in word: ...
print(letter) ... c a t ###### 11.8 Calculating a sum in a loop ``` While we have the Python built-in function sum() which sums the elements of a sequence (provided the elements of the sequence are all of numeric type), it’s instructive to see how we can do this in a loop (in fact, summing in a loop is exactl...
Since the elements of t are all numeric, we can calculate their sum. First, we create a variable to hold the result of the sum.
We call this, sum_.[7] Then, we iterate over all the elements in t, and at each iteration of the loop, we add the value of each element to the variable sum_.
Once the loop has terminated, sum_ holds the sum of all the elements of t.
Then we print, and compare with the result returned by sum(t) to verify this is indeed the correct result. In calculations like this we call the variable, sum_, an accumulator (because it accumulates the values of the elements in the iteration). That’s how we calculate a sum in a loop! ###### 11.9 Loops and summations...
The summation is a loop! In the formula above, there’s some list of values, 𝑥 indexed by 𝑖.
The summation says: “Take all the elements, 𝑥𝑖, and sum them.” The summation portion is just 𝑁−1 ∑ 𝑥𝑖 𝑖=0 which is the same as 𝑥0 + 𝑥1 + … + 𝑥𝑁−2 + 𝑥𝑁−1 Here’s the loop in Python (assuming we have some list called x): ``` s = 0 for e in x: s = s + e ``` after which, we’d divide by the number ...
Exactly this! 7Why do we use the trailing underscore? To avoid overwriting the Python builtin function sum() with a new definition. ----- Here’s another.
Let’s say we wanted to calculate the sum of the squares of a list of numbers (which is common enough).
Here’s the summation notation (again using zero indexing): 𝑁−1 ∑ 𝑥[2]𝑖 𝑖=0 Here’s the loop in Python: ``` s = 0 for e in x: s = s + e ** 2 ``` See?
The connection between summations and loops is straightforward. ###### 11.10 Products The same applies to products.
Just as we can sum by adding all the elements in some list or tuple of numerics, we can also take their product by multiplying.
For this, instead of the symbol ∑, we use the symbol Π (that’s an upper-case Π to distinguish it from the constant 𝜋). 𝑁−1 ∏ 𝑥𝑖 𝑖=0 This is the same as 𝑥0 × 𝑥1 × … × 𝑥𝑁−2 × 𝑥𝑁−1 The corresponding loop in Python: ``` p = 1 for e in x: p = p * e ``` Why do we initialize the accumulator to 1?
Because that’s the multiplicative identity. If we set this equal to zero the product would be zero, because anything multiplied by zero is zero. Anything multiplied by one is itself.
Thus, if calculating a repeated product, we initialize the accumulator to one. ###### 11.11 enumerate() We’ve seen how to iterate over the elements of an iterable in a for loop. ``` for e in lst: print(e) ``` Sometimes, however, it’s helpful to have both the element and the index of the element at each iterat...
One common application requiring an element and the index of the element is in calculating an alternating ----- _sum.
Alternating sums appear in analysis, number theory, combinatorics,_ many with real-world applications. An alternating sum is simply a summation where the signs of terms alternate.
Rather than 𝑥0 + 𝑥1 + 𝑥2 + 𝑥3 + 𝑥4 + 𝑥5 + … where the signs are all positive, an alternating sum would look like this: 𝑥0 −𝑥1 + 𝑥2 −𝑥3 + 𝑥4 −𝑥5 + … Notice that we alternate addition and subtraction. There are many ways we could implement this.
Here’s one rather clunky example (which assumes we have a list of numerics named lst): ``` alternating_sum = 0 for i in range(len(lst)): if i % 2: # i is odd, then we subtract alternating_sum -= lst[i] else: alternating_sum += lst[i] ``` This works.
Strictly speaking from a mathematical standpoint it is correct, but for `i` `in` `range(len(lst)) and then using i as an index` into lst is considered an “anti-pattern” in Python.
(Anti-patterns are patterns that we should avoid.) So what’s a programmer to do? ``` enumerate() to the rescue! Python provides us with a handy built ``` in function called enumerate().
This iterates over all elements in some sequence and yields a tuple of the index and the element at each iteration. Here’s the same loop implemented using enumerate(): ``` alternating_sum = 0 for i, e in enumerate(lst): if i % 2: alternating_sum -= e else: alternating_sum += e ``` We do away ...
Say we wanted to increment every element in a list of numeric values by a constant.
Here’s how we can do this with ``` enumerate(). incr = 5 lst = [1, 2, 3, 4] for i, e in enumerate(lst): ``` ----- ``` lst[i] = e + incr ``` That’s it!
After this code has run, lst has the value [6, 7, 8, 9]. In many cases, use of enumerate() leads to cleaner and more readable code. But how does it work?
What, exactly, does enumerate() do? If we pass some iterable—say a list, tuple, or string—as an argument to enumerate() we get a new iterable object back, one of type enumerate (this is a new type we haven’t seen before).
When we iterate over an enumerate object, it yields tuples. The first element of the tuple is the index of the element in the original iterable.
The second element of the tuple is the element itself. That’s a lot to digest at first, so here’s an example: ``` lst = ['a', 'b', 'c', 'd'] for i, element in enumerate(lst): print(f"The element at index {i} is '{element}'.") ``` This prints: ``` The element at index 0 is 'a'. The element at index 1 is 'b...
When using enumerate() this comes in really handy. We use one variable to hold the index and one to hold the element. ``` enumerate() yields a tuple, and we unpack it on the fly to these two ``` variables. Let’s dig a little deeper using the Python shell. ``` >>> lst = ['a', 'b', 'c'] >>> en = enumerate(lst) >>>...
print(t) ... (0, 'a') (1, 'b') (2, 'c') ``` So you see, what’s yielded at each iteration is a tuple of index and element.
Pretty cool, huh? Now that we’ve learned a little about enumerate() let’s revisit the alternating sum example: ----- ``` alternating_sum = 0 for i, e in enumerate(lst): if i % 2: alternating_sum -= e else: alternating_sum += e ``` Recall that we’d assumed lst is a previously defined list...
When we pass lst as an argument to enumerate() we get an ``` enumerate object. When we iterate over this object, we get tuples at each ``` iteration. Here we unpack them to variables i and e.
i is assigned the index, and e is assigned the element. If you need both the element and its index, use enumerate(). ###### 11.12 Tracing a loop Oftentimes, we wish to understand the behavior of a loop that perhaps we did not write.
One way to suss out a loop is to use a table to trace the execution of the loop.
When we do this, patterns often emerge, and—in the case of a while loop—we understand better the termination criteria for the loop. Here’s an example.
Say you were asked to determine the value of the variable s after this loop has terminated: ``` s = 0 for n in range(1, 10): if n % 2: # n is odd; 1 is truthy s = s + 1 / n else: # n must be even; 0 is falsey s = s - 1 / n ``` Let’s make a table, and fill it out.
The first row in the table will represent our starting point, subsequent rows will capture what goes on in the loop.
In this table, we need to keep track of two things, n and s. ``` n s ``` 0 Before we enter the loop, s has the value 0. Now consider what values we’ll be iterating over.
range(1, 10) will yield the values 1, 2, 3, 4, 5, 6, 7, 8 and 9.
So let’s add these to our table (without calculating values for s yet). ----- ``` n s ``` 0 1 ? 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? Since there are no break or return statements, we know we’ll iterate over all these values of n. Now let’s figure out what happens to s within the loop.
At the first iteration, n will be 1, which is odd, so the if branch will execute. This will add 1 / n to s, so at the end of the first iteration, s will equal 1 (1 ``` / 1).
So we write that down in our table: ``` ----- ``` n s ``` 0 1 1 2 ? 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? Now for the next iteration. At the next iteration, n takes on the value 2.
Which branch executes? Well, 2 is even, so the else branch will execute and 1/2 will be subtracted from s.
Let’s not perform decimal expansion, so we can write: ``` n s ``` 0 1 1 2 1 −1/2 3 ? 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? Now for the next iteration.
n takes on the value 3, 3 is odd, and so the if branch executes and we add 1/3 to s.
Again, let’s not perform decimal expansion (not doing so will help us see the pattern that will emerge). ``` n s ``` 0 1 1 2 1 −1/2 3 1 −1/2 + 1/3 4 ? 5 ? 6 ? 7 ? 8 ? 9 ? Now for the next iteration.
n takes on the value 4, 4 is even, and so the else branch executes and we subtract 1/4 to s. ----- ``` n s ``` 0 1 1 2 1 −1/2 3 1 −1/2 + 1/3 4 1 −1/2 + 1/3 −1/4 5 ? 6 ? 7 ? 8 ? 9 ? Do you see where this is heading yet?
No? Let’s do a couple more iterations. At the next iteration. n takes on the value 5, 5 is odd, and so the if branch executes and we add 1/5 to s.
Then n takes on the value 6, 6 is even, and so the else branch executes and we subtract 1/6 to s. ``` n s ``` 0 1 1 2 1 −1/2 3 1 −1/2 + 1/3 4 1 −1/2 + 1/3 −1/4 5 1 −1/2 + 1/3 −1/4 + 1/5 6 1 −1/2 + 1/3 −1/4 + 1/5 −1/6 7 ? 8 ? 9 ? At this point, it’s likely you see the pattern (if not, just work out two or th...
This loop is calculating 1 − [1] 2 [+ 1]3 [−1]4 [+ 1]5 [−1]6 [+ 1]7 [−1]8 [+ 1]9 See? At each iteration, we’re checking to see if n is even or odd.
If n is odd, we add 1 / n; if n is even, we subtract 1 / n. We can write this more succinctly using summation notation.
This loop calculates 𝑛=9 𝑠= ∑(−1)[𝑛−1][ 1] 𝑛=1 𝑛 [.] You may ask yourself: What’s up with the (−1)[𝑛−1] term? That’s handling the alternating sign! - What’s (−1)[0]? 1. - What’s (−1)[1]?
-1. - What’s (−1)[2]? 1. ----- - What’s (−1)[3]? -1. - What’s (−1)[4]?
1. ###### Another example: factorial In mathematics, the factorial of a natural number, 𝑛 is the product of all the natural numbers up to and including 𝑛.
It is written with an exclamation point, for example, 6 !
= 1 × 2 × 3 × 4 × 5 × 6. Let’s trace a Python loop which calculates factorial. ``` n = 6 f = 1 for i in range(2, n + 1): f = f * i ``` What does this loop do?
At each iteration, it multiplies 𝑓 by 𝑖 and makes this the new 𝑓. ``` i f ``` 1 2 2 3 6 4 24 5 120 6 720 This calculates factorial, 𝑛! for some 𝑛.
(Yes, there are easier ways.) Remember: 𝑛!
= 𝑖=𝑛 ∏ 𝑖. 𝑖=1 ###### Another example: discrete population growth ``` birth_rate = 0.05 death_rate = 0.03 pop = 1000 # population n = 4 for _ in range(n): pop = int(pop * (1 + birth_rate - death_rate)) ``` ----- ``` _ p ``` 1000 1 1020 2 1040 3 1060 4 1081 Here we don’t use...
In this example, we multiply the old pop by (1 + birth_rate - death_rate) and make this the new pop at each iteration.
This one’s a nuisance to work out by hand, but with a calculator it’s straightforward. What is this calculating?
This is calculating the size of a population which starts with 1000 individuals, and which has a birth rate of 5% and a death rate of 3%.
This calculates the population after four time intervals (for example, years). Being able to trace through a loop (or any portion of a program) is a useful skill for a programmer. ###### 11.13 Nested loops It’s not uncommon that we include one loop within another.
This is called nesting, and such loops are called nested loops. Let’s say we wanted to print out pairings of contestants in a round robin chess tournament (a “round robin” tournament is one in which each player plays each other player).
Because in chess white has a slight advantage over black, it’s fair that each player should play each other player twice: once as black and once as white. We’ll represent each game with the names of the players, in pairs, where the first player listed plays white and the second plays black. So in a tiny tournament with...
One way is with a nested loop. ----- ``` players = ['Anne', 'Bojan', 'Carlos', 'Doris'] for white in players: for black in players: if white != black: # exclude self-pairings print(f"{white} (W) vs {black} (B)") ``` This code, when executed, prints exactly the list of pairings shown above. Ho...
The outer loop—for white in players:—iterates over all players, one at a time: Anne, Bojan, Carlos, and Doris.