Skip to content

Instantly share code, notes, and snippets.

@sidmitra
Created December 26, 2016 21:11
Show Gist options
  • Save sidmitra/1a1bcf62e05b43dd5aeacecf6c7efb1f to your computer and use it in GitHub Desktop.
Save sidmitra/1a1bcf62e05b43dd5aeacecf6c7efb1f to your computer and use it in GitHub Desktop.
Flatten arbitrary nested lists in Python
def flatten(lst):
for item in lst:
# if item is a sublist
if isinstance(item, (list,tuple)):
# flatten sublist
for j in flatten(item):
yield j
else:
yield item
# list(flatten([[1,2,3], [[4], [5], [6]], [7,8,9]]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment