Iterators & Generators
Shayna Kothari
Iterators
Iterators Example
>>> lst = [1, 2]�>>> p, q = iter(lst), iter(lst)�>>> next(p)�1�>>> next(p)�2�>>> next(q)�1�>>> lst.append(3)�>>> next(p)�3�>>> next(p)�StopIterationError
1
2
1
2
p
q
1
2
q
1
2
p
q
1
2
p
q
1
2
p
q
3
p
1
2
p
q
3
1
2
p
q
3
Generators
Generators: Bookmarking
>>> def gen(x):
... print('hi!')
... i = 0
... while i < x:
... print('iteration', i)
... yield i
... i += 1
...
>>> p = gen(4)
>>> next(p)
hi!
iteration 0
0
>>> next(p)
iteration 1
1
Generators
def gen(n):
i = 0
while i < n:
yield i
i += 1
Recursive Generators
for i in some_iterator:
yield i
yield from some_iterator
=
Problem Solving Tip: When dealing with generators recursively, pretend you’re getting a list of values back from the generator function instead of a generator! (However, remember not to yield that list!)
Recursive Generators
def increasing_lists(lst):
'''
Generate all sublists of lst that are in increasing order.
'''
if len(lst) != 0:
yield [lst[0]]
if len(lst) > 1:
for next_lst in increasing_lists(lst[1:]):
if next_lst[0] > lst[0]:
yield [[lst[0]] + next_lst
yield next_lst
Note: we don’t use yield from here because we have an if statement inside of our loop!