Created
December 26, 2016 21:11
-
-
Save sidmitra/1a1bcf62e05b43dd5aeacecf6c7efb1f to your computer and use it in GitHub Desktop.
Flatten arbitrary nested lists in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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