Skip to content

Instantly share code, notes, and snippets.

@zhoudaxia233
Last active June 22, 2018 19:21
Show Gist options
  • Save zhoudaxia233/a63dab7545d82a35170c501db5243627 to your computer and use it in GitHub Desktop.
Save zhoudaxia233/a63dab7545d82a35170c501db5243627 to your computer and use it in GitHub Desktop.
Flatten a list in python
flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]

# Below is for you to understand 
# flatten = lambda x: [item for items in itemss for item in flatten(items)] if type(itemss) is list else [itemss]

>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten(a)
[1,2,3,4,5,6,7,8]


>>> b = 5
>>> flatten(b)
[5]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment