Skip to content

Instantly share code, notes, and snippets.

@sseg
Created May 11, 2015 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sseg/42dd88d44804e43342ca to your computer and use it in GitHub Desktop.
Save sseg/42dd88d44804e43342ca to your computer and use it in GitHub Desktop.
Flatten nested iterators of (nearly) arbitrary depth in Python 3.3+
def flattener(Xs):
"""flattener takes an object, Xs, which if iterable is recursively flattened
yielding non-iterable objects, subject to any maximum recursion depth limits
"""
if hasattr(Xs, "__iter__"):
for x in Xs:
yield from flattener(x)
else:
yield Xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment