Skip to content

Instantly share code, notes, and snippets.

@lukasz-madon
Created March 7, 2017 00:05
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 lukasz-madon/8a707a6ae3968d3c41eda3dbede7a079 to your computer and use it in GitHub Desktop.
Save lukasz-madon/8a707a6ae3968d3c41eda3dbede7a079 to your computer and use it in GitHub Desktop.
Flatten python collection
# following code uses recursion, so it may run out of stack memeory for large collections
def flatten(container):
"""generate a flatten sequence from the input list"""
for i in container:
if isinstance(i, (list, tuple)):
for j in flatten(i):
yield j
else:
yield i
print list(flatten([])) == []
print list(flatten([[1 ,2, [3]], 4])) == [1, 2, 3, 4]
print list(flatten([1, 2, [3, 4, [5], [34]], [6, [[[7, 89]]]]])) == [1, 2, 3, 4, 5, 34, 6, 7, 89]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment