0

I have a list that holds several sublist, each one of them with a given number of elements inside. I need to move all elements inside all sublists into another list, ie: remove the separation among elements imposed by the sublists.

This is a MWE if what I mean:

a = [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], [[17, 18, 19, 20], [21, 22, 23, 24]], [[25, 26, 27, 28], [26, 30, 31, 32], [33, 34, 35, 36]]]

b = []
    for elem in a:
        for item in elem:
            b.append(item)

which results in:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [26, 30, 31, 32], [33, 34, 35, 36]]

I'm sure there's a more elegant and simpler way to do this in python.

Gabriel
  • 40,504
  • 73
  • 230
  • 404
  • see here http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python – jaap Nov 01 '13 at 17:30

2 Answers2

2

Use itertools.chain.from_iterable:

>>> from itertools import chain
>>> list(chain.from_iterable(a))
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24], [25, 26, 27, 28], [26, 30, 31, 32], [33, 34, 35, 36]]

Timing comparison:

enter image description here

Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

Try this:

[item for sublist in a for item in sublist]
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • This works perfectly but I marked the other answer as accepted because,as the author stated, it is much faster. Thanks you very much! – Gabriel Nov 01 '13 at 18:15