75

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
codious
  • 3,377
  • 6
  • 25
  • 46
  • 12
    `[item for sublist in l for item in sublist]`. This is a duplicate of a number of other questions. See, for example, http://stackoverflow.com/q/952914/623518, http://stackoverflow.com/q/406121/623518 and http://stackoverflow.com/q/457215/623518. – Chris Aug 08 '12 at 08:25
  • @zrxq It isn't that question but it is a duplicate of the ones mentioned by Chris – jamylak Aug 08 '12 at 08:27

4 Answers4

85

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]
Community
  • 1
  • 1
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
  • 2
    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 Mar 20 '19 at 12:30
  • 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. – moooeeeep Mar 20 '19 at 14:38
  • 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'] – msh855 Mar 20 '19 at 14:58
  • 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. – moooeeeep Mar 20 '19 at 17:09
42

Use reduce function

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

Or sum

sum(A, [])
lollo
  • 2,289
  • 16
  • 20
7

the first case can also be easily done as:

A=A[0]
codious
  • 3,377
  • 6
  • 25
  • 46
  • 15
    the OP wrote that `[[1,2], [3,4]]` should turn into `[1,2,3,4]`. Your solution returns `[1,2]`! – Qaswed Mar 06 '20 at 13:03
6

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

nd.
  • 8,699
  • 2
  • 32
  • 42