Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python Generator Cheatsheet
# A personal cheatsheet for the confusing (to me) python feature: generators
# Done in ipython
[n*2 for n in [1,2,3]]
# Out[8]: [2, 4, 6]
{n*2 for n in [1,2,3] if n > 1}
# Out[9]: {4, 6}
for n in (x for x in [1,2,3] if x > 1):
print(n*3)
# 6
# 9
# Generators
def abc():
return 1
return 2
return 3
abc()
# 1
abc()
# 1
# useless because return short-circuits, just showing this as compared to what's next
# More useful:
def abc():
yield 1
yield 2
[ print(x) for x in abc() ]
# 1
# 2
# Save handle to generator:
gen = abc()
next(gen)
# Out[34]: 1
next(gen)
# Out[35]: 2
# you can't keep going
next(gen)
# ---------------------------------------------------------------------------
# StopIteration Traceback (most recent call last)
# <ipython-input-36-6e72e47198db> in <module>()
# ----> 1 next(gen)
# StopIteration:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment