Last active
August 29, 2015 14:05
-
-
Save jepio/c06cb53bd626041eb820 to your computer and use it in GitHub Desktop.
An advanced (kind of) generator example.
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
def flatten(iterable): | |
try: | |
if isinstance(iterable, (str, bytes)): # are recursively iterable | |
raise TypeError # could've just as well been yield iterable, then else is needed | |
for item in iterable: | |
yield from flatten(item) | |
## alternative (py2): | |
# for nested in flatten(item): | |
# yield nested | |
except TypeError: | |
yield iterable | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment