Created
October 5, 2018 22:41
-
-
Save squarism/6988fdadb2901d11868dacabe8b97b46 to your computer and use it in GitHub Desktop.
Python Generator Cheatsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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