Given a multidimensional (nested) Python list, how can I easily get a single list that contains all the elements of its sub-lists?
For example, given [[1,2,3,4,5]] I want to get [1,2,3,4,5]; similarly [[1,2], [3,4]] should become [1,2,3,4].
Use itertools.chain:
itertools.chain(*iterables):Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.
from itertools import chain
A = [[1,2], [3,4]]
print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))
The output is:
[1, 2, 3, 4]
[1, 2, 3, 4]
itertools provides the chain function for that:
From http://docs.python.org/library/itertools.html#recipes:
def flatten(listOfLists):
"Flatten one level of nesting"
return chain.from_iterable(listOfLists)
Note that the result is an iterable, so you may need list(flatten(...)).
the first case can also be easily done as:
A=A[0]
[[1,2], [3,4]] should turn into [1,2,3,4]. Your solution returns [1,2]!
[item for sublist in l for item in sublist]. This is a duplicate of a number of other questions. See, for example, stackoverflow.com/q/952914/623518, stackoverflow.com/q/406121/623518 and stackoverflow.com/q/457215/623518.