Skip to content

Instantly share code, notes, and snippets.

@mrluanma
Forked from andelf/flatten.py
Created December 15, 2011 11:07
Show Gist options
  • Save mrluanma/1480728 to your computer and use it in GitHub Desktop.
Save mrluanma/1480728 to your computer and use it in GitHub Desktop.
How to flatten a python nested list(tuple)
flatten = lambda lst: reduce(lambda l, i: l + flatten(i) if isinstance(i, (list, tuple)) else l + [i], lst, [])
print flatten([2, [2, [4, 5, [7], [2, [6, 2, 6, [6], 4]], 6]]])
# -> [2, 2, 4, 5, 7, 2, 6, 2, 6, 6, 4, 6]
@shaxbee
Copy link

shaxbee commented Nov 19, 2014

I've stumbled upon this gist in google search results :-)

I've made tail-recursive python 3 version available here: https://gist.github.com/shaxbee/0ada767debf9eefbdb6e

@ma-ric
Copy link

ma-ric commented May 21, 2015

enhanced version of shaxbee's solution, https://gist.github.com/ma-ric/451ce328c4c84d18c8af

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