Skip to content

Instantly share code, notes, and snippets.

@tmehlinger
Last active September 7, 2016 19:50
Show Gist options
  • Save tmehlinger/243c2fbf5bc5ed52e694c2930f54aab7 to your computer and use it in GitHub Desktop.
Save tmehlinger/243c2fbf5bc5ed52e694c2930f54aab7 to your computer and use it in GitHub Desktop.
flatten arbitrarily nested iterables
from collections.abc import Iterable
def flatten(seq, maxdepth=10):
if maxdepth <= 0:
raise ValueError
if isinstance(seq, Iterable) and not isinstance(seq, str):
for item in seq:
yield from flatten(item, maxdepth - 1)
else:
yield seq
if __name__ == '__main__':
print(list(flatten([5, [1], [2], [[3], [4, 7, 'bar'], 6, 'foo']])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment