1

Which is the most pythonic way and the fastest way (could be the same) to append many list together? For example, given the lists below:

a = [1, 2]
b = [3, 4]
c = [5, 6]
d = [7, 8]

we get one list:

combined = [1, 2, 3, 4, 5, 6, 7, 8]
km1234
  • 2,127
  • 4
  • 18
  • 21
  • what have you tried so far? – slackmart Aug 26 '18 at 01:55
  • Possible duplicate of [join list of lists in python](https://stackoverflow.com/questions/716477/join-list-of-lists-in-python) – bla Aug 26 '18 at 01:58
  • @slackmart: simple loop and list comprehension (more pythonic than simple loop), not sure if the fastest or most pythonic though – km1234 Aug 26 '18 at 02:01

3 Answers3

2

In Python 3.5+, you can use the generic unpacking:

combined = [*a, *b, *c, *d]

or prior to Python 3.5+, you can use itertools.chain:

from itertools import chain
combined = list(chain(a, b, c, d))
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

I can't understand you do you mean how to merge them? for example

a = [1, 2]
b = [3, 4]
c = [5, 6]
d = [7, 8]
combined = a + b + c + d 

so combined will be

[1, 2, 3, 4, 5, 6, 7, 8]
Mina Ragaie
  • 457
  • 6
  • 17
  • 3
    While this solution is easy to read, it is less efficient because with every `+` operation a new list is created with the lists in both operands copied to the new list. – blhsing Aug 26 '18 at 02:43
0

OR:

a = [1, 2]
b = [3, 4]
c = [5, 6]
d = [7, 8]
a.extend(b)
a.extend(c)
a.extend(d)

Now:

print(a)

Returns:

[1, 2, 3, 4, 5, 6, 7, 8]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114