82

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].

2

4 Answers 4

91

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.

Example:

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]
Sign up to request clarification or add additional context in comments.

4 Comments

It useful to clarify that all objects within the list must be lists themselves. For example, if 'A= ['year', [1] ]' then 'chain' will not produce the expected results. It requires 'A = [['year'], [1]]'.
@msh855 A string is an iterable too. So, in this case, it seems to be more an issue with the expectation, rather than with the result.
Have you tried it, or is indeed a matter of expectation?. I tried this: A= ['year', [1,2,'bad']] list(chain(*A)) list(chain.from_iterable(A)) and produced: Out[153]: ['y', 'e', 'a', 'r', 1, 2, 'bad']
You pass two iterables, both of which are iterated. The first produces the characters in the string, the second produces the list elements. If you need a different behavior, you might need to write specific code.
42

Use reduce function

reduce(lambda x, y: x + y, A, [])

Or sum

sum(A, [])

1 Comment

reduce was removed in Python 3. The sum version works but the itertools.chain method is much faster.
7

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(...)).

Comments

4

the first case can also be easily done as:

A=A[0]

1 Comment

the OP wrote that [[1,2], [3,4]] should turn into [1,2,3,4]. Your solution returns [1,2]!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.