-
-
Save mrluanma/1480728 to your computer and use it in GitHub Desktop.
How to flatten a python nested list(tuple)
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
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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