Skip to content

Instantly share code, notes, and snippets.

@gauravvjn
Created May 1, 2018 13:23
Show Gist options
  • Save gauravvjn/ad6873a5fe17821bf0b0624b602b70e4 to your computer and use it in GitHub Desktop.
Save gauravvjn/ad6873a5fe17821bf0b0624b602b70e4 to your computer and use it in GitHub Desktop.
flatten a python list of lists
# 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