Skip to content

Instantly share code, notes, and snippets.

@jay3686
Created March 5, 2014 21:05
Show Gist options
  • Save jay3686/9376565 to your computer and use it in GitHub Desktop.
Save jay3686/9376565 to your computer and use it in GitHub Desktop.
flatting list of lists or non lists
"""
In [56]: a = [1,[2,3,4], 4,5,6, [7,8], 9, 10]
In [57]: normalize = lambda x : x if type(x) == list else [x]
In [58]: list(itertools.chain(*map(normalize, a)))
Out[58]: [1, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10]
In [59]: a
[1, [2, 3, 4], 4, 5, 6, [7, 8], 9, 10]
"""
a = [1,[2,3,4], 4,5,6, [7,8], 9, 10]
normalize = lambda x : x if type(x) == list else [x]
list(itertools.chain(*map(normalize, a)))
# list() on iterator only to show results in this example. normally
# you would iterate instead of trying to put the whole list in
# memory at once.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment