In Peter Norvig's MOOC, he introduces list comprehensions to teach generator expressions. Let's have a look at them.
You can have lots of fors and ifs in list comprehensions.
print([p + q + r for p in 'ABC' for q in 'DEF' for r in 'GHI' if q == 'E'])
['AEG', 'AEH', 'AEI', 'BEG', 'BEH', 'BEI', 'CEG', 'CEH', 'CEI']
This works because everything is nested. List comprehensions make for loops flat. This is elegant.
Short way of doing: use parentheses.
g = (x for x in range(3))
g
<generator object <genexpr> at 0x104277ca8>
next(g)
0
next(g)
1
next(g)
2
next(g)
--------------------------------------------------------------------------- StopIteration Traceback (most recent call last) <ipython-input-13-5f315c5de15b> in <module>() ----> 1 next(g) StopIteration:
Uuuuhhuhh there's a StopIteration!!!
In practice, we'll use a for loop. This doesn't raise any errors!
g = (x for x in range(3))
for x in g:
print(x)
0 1 2
Also, this works with lists:
g = (x for x in range(3))
list(g)
[0, 1, 2]
A simple do nothing generator.
def gen(l):
for item in l:
yield item
for x in gen([1, 2, 3]):
print(x)
1 2 3
A reverser!
def gen_reverse(l):
for item in reversed(l):
yield(item)
for x in gen_reverse([1, 2, 3]):
print(x)
3 2 1