Skip to content

Instantly share code, notes, and snippets.

@jepio
Last active August 29, 2015 14:05
Show Gist options
  • Save jepio/c06cb53bd626041eb820 to your computer and use it in GitHub Desktop.
Save jepio/c06cb53bd626041eb820 to your computer and use it in GitHub Desktop.
An advanced (kind of) generator example.
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