Created
May 1, 2018 13:23
-
-
Save gauravvjn/ad6873a5fe17821bf0b0624b602b70e4 to your computer and use it in GitHub Desktop.
flatten a python list of lists
This file contains hidden or 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
# source: flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x] | |
def flatten(x): | |
if type(x) == list: | |
a = [] | |
for l in x: | |
for y in flatten(l): | |
a.append(y) | |
return a | |
else: | |
return [x] | |
# ----------------- demo ---------------------- | |
>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]] | |
>>> flatten(a) | |
[1, 2, 3, 4, 5, 6, 7, 8] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment