Skip to content

Instantly share code, notes, and snippets.

@adammartinez271828
Last active August 3, 2016 01:08
Show Gist options
  • Select an option

  • Save adammartinez271828/2b84dc91fc54fb8871787b0c41175666 to your computer and use it in GitHub Desktop.

Select an option

Save adammartinez271828/2b84dc91fc54fb8871787b0c41175666 to your computer and use it in GitHub Desktop.
Flatten arbitrary nested lists
def flatten(iterable):
"""Return a generator that flattens an iterable
Safe to use on nested iterables.
Args:
iterable: any iterable.
Returns:
generator of all items in iterable
Example:
>>> list(flatten([1, [2, 3], [4, [5, 6]]]))
[1, 2, 3, 4, 5, 6]
"""
for element in iterable:
try:
yield from flatten(element)
except TypeError:
yield element
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment