from itertools import permutations, product, repeat
import numpy as npSo far, we have used for loops over lists like
a = [1,2,3]
for x in a:
print(x)This looks very different from a C-style for loop where we loop over the variable index:
for (size_t i = 0; i < 3; i++) {
printf("%d\n", i);
}Or for instance, we can use something called a range
for i in range(3):
print(i)or other data types
d = {"hello": 1, "goodbye": 2}
for k,v in d.items():
print(k, ' : ', v)The key to using this sort of syntax is the concept of iterator. This is common in object-oriented programming (not just in Python), but you probably haven’t seen iterators before if you’ve only used imperative languages.
An object is iterable if it implements the __iter__ method, which is expected to return an iterator object.
An object is an iterator if it implements the __next__ method, which either
returns the next element of the iterable object
raises the
StopIterationexception if there are no more elements to iterate over
Informally, an iterable is something you can loop over, like a list, a string, or a range. An iterator is the object that remembers how far the loop has gotten and hands out the elements one at a time. The built-in functions iter(x) and next(it) call x.__iter__() and it.__next__() for us.
A Basic Iterator¶
What if we want to replicate range?
r = range(3)
print(r, type(r))we can produce an iterator using the iter function
ri = iter(r)
type(ri)we can explicitly run through the iterator using the next function
next(ri)r = range(1,5,2)
ri = iter(r)
print(next(ri))
print(next(ri))
Each call to next moves the iterator forward by one element. range(1, 5, 2) only contains 1 and 3, so a third call has nothing left to return, and next raises a StopIteration exception instead:
next(ri)This is how a for loop knows when to stop. A loop like for x in a: first calls iter(a) to get an iterator, then calls next on that iterator over and over until it raises StopIteration. Written out by hand, the loop from the top of this page is roughly
it = iter(a) # get an iterator from the iterable
while True:
try:
x = next(it) # ask the iterator for the next element
except StopIteration:
break # no elements left, so the loop ends
print(x)An iterator only moves forward, and once it is exhausted it stays exhausted. The iterable is not used up, though. Every call to iter creates a new iterator that starts from the beginning, which is why we can loop over the same list or range as many times as we want.
ri = iter(r)
print(list(ri)) # list() runs through the whole iterator
print(list(ri)) # ri is exhausted, so there is nothing left
print(list(r)) # r itself is fine: list() calls iter(r) and gets a new iteratorTo replicate range, we write two classes. my_range is the iterable: it stores start, stop, and stride, and its __iter__ method creates a new iterator.
my_range_iterator is the iterator: it stores the current position in self.state, and each call to __next__ returns the current value and then moves state forward by stride. Once state reaches stop, it raises StopIteration.
class my_range(object):
"""
A class for an iteratble oject
"""
def __init__(self, start, stop, stride=1):
self.start = start
self.stop = stop
self.stride = stride
def __iter__(self):
return my_range_iterator(self.start, self.stop, self.stride)
class my_range_iterator(object):
"""
A class for an iterator created by my_range
"""
def __init__(self, start, stop, stride):
self.state = start
self.stop = stop
self.stride = stride
def __next__(self):
if self.state >= self.stop:
raise StopIteration # signals "the end"
ret = self.state # we'll return current state
self.state += self.stride # increment state
return retr = my_range(0,3)
type(r)ri = iter(r)
type(ri)next(ri)for i in my_range(0,3):
print(i)for i in range(0,3):
print(i)You can also create classes that are both iterators and iterables
# an iterable and iterator
class my_range2(object):
def __init__(self, start, stop, stride=1):
self.start = start
self.stop = stop
self.stride = stride
self.state = start
def __iter__(self):
return self
def __next__(self):
if self.state >= self.stop:
raise StopIteration # signals "the end"
ret = self.state # we'll return current state
self.state += self.stride # increment state
return retBecause __iter__ returns self, a my_range2 object is its own iterator. Python’s built-in iterators work the same way: calling iter on an iterator gives back the iterator itself, which is why a for loop accepts an iterator as well as an iterable.
The catch is that the position state is now stored on the my_range2 object itself, so it can only be looped over once. my_range doesn’t have this problem, since every loop gets a fresh my_range_iterator:
r = my_range(0, 3)
print(list(r))
print(list(r)) # each call to list() gets a new my_range_iterator
r2 = my_range2(0, 3)
print(list(r2))
print(list(r2)) # r2 is its own iterator, and the first list() used it upUsing Iterators for Computation¶
Let’s now use iterators for something more interesting - computing the Fibonacci numbers.
class FibonacciIterator(object):
def __init__(self):
self.a = 0 # current number
self.b = 1 # next number
def __iter__(self):
return self
def __next__(self):
ret = self.a
self.a, self.b = self.b, self.a + self.b # advance the iteration
return retfor i in FibonacciIterator():
if i > 1000:
break
print(i)Note that we never raise a StopIteration exception - the iterator will just keep going if we let it.
A list could never do this. The Fibonacci sequence is infinite, so there is no way to store all of it, but the iterator doesn’t have to: it only computes the next number when the loop asks for one. This is called lazy evaluation. In the loop above, the break is what stops the iteration. Be careful with infinite iterators: something like list(FibonacciIterator()) never finishes.
Exercise¶
Define FibonacciIterator so it will iterate over all Fibonacci numbers until they are greater than a parameter n.
## Your code here
Generators¶
Often, a more elegant way to define an iterator is using a generator
This is a special kind of iterator defined using a function instead of using classes that implement the __iter__ and __next__ methods.
See this post for more discussion.
def my_range3(state, stop, stride=1):
while state < stop:
yield state
state += stride
Note that we use the def keyword instead of the class keyword for our declaration. The yield keyword returns subsequent values of the iteration.
r = my_range3(0,3)
type(r)ri = iter(r)
type(ri)iter(r) returned r itself (you can check that ri is r). A generator is its own iterator, like my_range2, so it can only be looped over once.
next(ri)for i in my_range3(0,3):
print(i)How yield works¶
A generator function doesn’t run like a normal function. Calling my_range3(0, 3) doesn’t run any of the code in its body; it only creates a generator object. Each call to next then runs the body until it reaches a yield. next returns the yielded value, and the function pauses right there, keeping its local variables. The following call to next resumes right after the yield. When the function returns (at a return statement or by reaching the end of its body), the generator raises StopIteration.
So my_range3 does the same job as the my_range2 class with much less code: Python writes the __iter__ and __next__ methods for us, and the local variables state, stop, and stride take the place of the attributes on self.
Adding some print statements shows the order in which things happen:
def verbose_range(stop):
print(" generator: start")
i = 0
while i < stop:
print(f" generator: yield {i}")
yield i
print(f" generator: resume after yielding {i}")
i += 1
print(" generator: end of function")
g = verbose_range(2)
print("created g") # nothing from the body of verbose_range has run yetprint("next returned", next(g))
print("next returned", next(g))next(g) # resumes after yielding 1, leaves the while loop, and reaches the endOur Fibonacci example re-written using a generator. The attributes self.a and self.b of FibonacciIterator become local variables, which the generator keeps between calls to next:
def FibonacciGenerator():
a = 0
b = 1
while True:
yield a
a, b = b, a + bfor i in FibonacciGenerator():
if i > 1000:
break
print(i)
Exercise¶
Define FibonacciGenerator so it will iterate over all Fibonacci numbers until they are greater than a parameter n.
## Your code here
def FibonacciGenerator(n):
a = 0
b = 1
while a < n:
yield a
a, b = b, a + b
for i in FibonacciGenerator(1000):
print(i)Generator expressions¶
For short generators there is a shorthand that looks like a list comprehension with parentheses instead of square brackets. A list comprehension computes every element right away and stores them all in a list. A generator expression creates a generator, which computes the elements one at a time as they are asked for.
squares_list = [i**2 for i in range(5)] # all five values are computed now
squares_gen = (i**2 for i in range(5)) # nothing is computed yet
print(squares_list)
print(squares_gen)
print(list(squares_gen))A generator only stores its current state, so its size doesn’t depend on how many values it will produce. If you only need to go through the values once, for example to add them up, a generator expression saves you from building the whole list first.
import sys
n = 1_000_000
# getsizeof counts the list's references to its elements, not the integers themselves,
# so the list actually uses even more memory than this
print(sys.getsizeof([i**2 for i in range(n)]), "bytes for the list")
print(sys.getsizeof((i**2 for i in range(n))), "bytes for the generator")
# a generator expression that is the only argument of a function needs no extra parentheses
sum(i**2 for i in range(n))Iteration tools¶
Some useful tools for iterators that come in handy are zip, reversed, and enumerate. Each of them returns an iterator, so like a generator, it produces its values lazily instead of building a list.
zip - iterates over multiple iterators simultaneously, stopping as soon as the shortest one runs out
for i, a in zip([0,1,2], ['a', 'b', 'c']):
print(i,a)reversed - iterates in reverse order. It has to start from the last element, so it works on sequences like lists, strings, and ranges, but not on generators, which can only move forward.
for i in reversed(range(3)):
print(i)enumerate - returns the iteration step count as well as the iterator value
for i, a in enumerate('abc'):
print(i, a)Exercise¶
Implement your own versions of zip and enumerate using generators
## Your code here
Notebook Cell
def my_zip(a, b):
ai = iter(a)
bi = iter(b)
while True:
try:
yield next(ai), next(bi)
except StopIteration:
# one of the inputs ran out. We have to catch this ourselves: if a
# StopIteration escapes from a generator's body, Python turns it into
# a RuntimeError (PEP 479). Returning ends the generator normally.
return
for i, a in my_zip(range(3), 'abc'):
print(i,a)Notebook Cell
def my_enumerate(a):
ct = 0
for x in a:
yield ct, x
ct = ct + 1
for i, a in my_enumerate('abcd'):
print(i, a)The Itertools Package¶
A useful package for dealing with iterators is the itertools package. Here are a few examples - click on the link to see what else the package provides.
product gives the equivalent of a nested for-loop
from itertools import product
for i, j in product(range(2), range(3)):
print(i, j)# equivalent to:
for i in range(2):
for j in range(3):
print(i,j)repeat just repeats a value
from itertools import repeat
for i in repeat(10, 5):
print(i)permutations
from itertools import permutations
for p in permutations(range(3)):
print(p)Exercise¶
Implement your own version of product and repeat using generators.
## Your code here
Notebook Cell
def my_product(a, b):
for x in a:
for y in b:
yield x, y
for x, y in my_product(range(2), range(3)):
print(x,y)Notebook Cell
def my_repeat(n, ct):
for i in range(ct):
yield n
for x in my_repeat(10, 5):
print(x)Iterators for Scientific Computing¶
One way you might use an iterator in scientific computing is when implementing an iterative algorithm.
Here is an example of gradient descent:
with a fixed step size . The gradient is zero at a minimum, so we stop once is small.
Writing the algorithm as a generator splits the work into two parts. The generator only knows how to take one step of the iteration, and it yields the current state after each step. The code that uses the generator decides what to do with each iterate and when to stop.
def GradientDescentGenerator(f, grad, x, alpha):
"""
gradient descent with a fixed step size alpha, starting from x
"""
while True:
g = grad(x)
# yield state: current point, value of f, and size of the gradient
yield x, f(x), np.linalg.norm(g)
x = x - alpha * g # compute next iterationAs a test problem, we minimize the quadratic
for a random symmetric positive definite matrix . Its gradient is , so the minimizer is the solution of , which lets us check the answer at the end. The eigenvalues of this lie between 1 and about 5, and gradient descent converges as long as .
rng = np.random.default_rng(37830)
n = 100
M = rng.standard_normal((n, n))
A = M @ M.T / n + np.eye(n) # symmetric positive definite
b = rng.standard_normal(n)
def f(x):
return 0.5 * x @ A @ x - b @ x
def grad(x):
return A @ x - b# here's a version that uses the generator in a while-loop
solver = GradientDescentGenerator(f, grad, np.zeros(n), alpha=0.3)
tol = 1e-4
while True:
x, fx, gnorm = next(solver)
print(fx, gnorm)
if gnorm < tol:
breakIf we decide that we’re not satisfied with convergence yet, we can resume where we left off. The generator is paused at its yield with the current x still stored in its local variables, so calling next again continues the iteration instead of starting over from .
tol = 1e-8
while True:
x, fx, gnorm = next(solver)
print(fx, gnorm)
if gnorm < tol:
breakThe result agrees with the solution of computed by np.linalg.solve:
np.linalg.norm(x - np.linalg.solve(A, b))You can do the same thing with for-loops. Breaking out of the first loop leaves the generator paused, not finished. The second loop calls iter(solver), which returns the same generator, so it picks up where the first loop stopped.
This time we use enumerate to count the steps instead of printing every iterate. A new enumerate starts counting from 0, so the second loop passes start=k + 1 to continue the count.
# here's a version that uses the generator in a for-loop
solver = GradientDescentGenerator(f, grad, np.zeros(n), alpha=0.3)
tol = 1e-4
for k, (x, fx, gnorm) in enumerate(solver):
if gnorm < tol:
break
print(f"|grad f| < {tol} after {k} steps")
tol = 1e-8
print('resuming iteration after decreasing tolerance')
for k, (x, fx, gnorm) in enumerate(solver, start=k + 1):
if gnorm < tol:
break
print(f"|grad f| < {tol} after {k} steps")