Skip to content

Instantly share code, notes, and snippets.

@squarism
Created October 5, 2018 22:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squarism/6988fdadb2901d11868dacabe8b97b46 to your computer and use it in GitHub Desktop.
Save squarism/6988fdadb2901d11868dacabe8b97b46 to your computer and use it in GitHub Desktop.
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