2

I have one list like: n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]

I want to create a function that takes a single list (see above) and concatenates all the sublists that are part of it into a single list.

user2469891
  • 31
  • 2
  • 3

4 Answers4

4
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
nn = [ x for y in n for x in y]
perreal
  • 94,503
  • 21
  • 155
  • 181
3
>>> lst = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
>>> from itertools import chain
>>> list(chain.from_iterable(lst))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Jared
  • 25,627
  • 7
  • 56
  • 61
2

For completeness, here is a very short way to write this

>>> sum(n, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

But although it is tempting, you shouldn't because it has quadratic performance. ie a new list is created as each term is added, and all the previous items will be copied over and over

It's ok to use list.extend though

reduce(lambda x,y: x.extend(y) or x, n, [])
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

You can also concatenate by doing simply:

print n[0]+n[1]

In general this would be:

def concatenate(list):
    x=[]
    for i in list:
        x+=i
    return x

But this is not particularly efficent, just quite straightforward for a beginner.

Ghostwriter
  • 2,461
  • 2
  • 16
  • 18