Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract nested lists? [duplicate]

Tags:

Duplicates:

  • Flattening a shallow list in Python
  • Comprehension for flattening a sequence of sequences?

Lets say I have a list with nested lists:

[["a","b","c"], ["d","e","f"], ["g","h","i","j"]...] 

what is the best way to convert it to a single list like that

["a", "b", "c", "d", "e"....] 
like image 423
user1040563 Avatar asked Nov 30 '11 14:11

user1040563


2 Answers

Use itertools.chain:

from itertools import chain  list(chain.from_iterable(list_of_lists)) 
like image 171
agf Avatar answered Sep 22 '22 06:09

agf


There's a straight forward example of this in the itertools documentation (see http://docs.python.org/library/itertools.html#recipes look for flatten()), but it's as simple as:

>>> from itertools import chain >>> list(chain(*x)) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

Or, it can be done very easily in a single list comprehension:

>>> x=[["a","b","c"], ["d","e","f"], ["g","h","i","j"]] >>> [j for i in x for j in i] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 

Or via reduce():

>>> from operator import add >>> reduce(add, x) ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] 
like image 33
Austin Marshall Avatar answered Sep 19 '22 06:09

Austin Marshall