How to concatenate two or multiple lists in Python

A list in Python is a data structure that holds an ordered collection of elements.

An operation to glue two lists together is called concatenation. You can concatenate two lists either in-place or out-of-place.

Suppose we have two lists to be concatenated,

list1 = [1, 2, 3, 4]
list2 = [5, 6, 7, 8]

We could have multiple methods to concatenate them, but they differ in the performance when the length increases or the number of concatenated lists increases.

We will introduce these different methods and give you the performance comparsion.

+ list concatenation method

+ operator could concatenate two lists and return a new list.

>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> result = list1 + list2
>>> result
[1, 2, 3, 4, 5, 6, 7, 8]

+= concatenation method

+= is similar to the above method, but it will change the data of the list before it in place.

>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> list1 += list2
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]

itertools.chain method

chain from itertools module treats consecutive sequences as one single sequence,

>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> import itertools
>>> result = list(itertools.chain(list1, list2))
[1, 2, 3, 4, 5, 6, 7, 8]
Information

itertools.chain has an alternate constructor - intertools.chain.from_iterable(). It has a single iterable argument whose inputs is evaluated lazily.

extend() method

List extend method extends list by appending elements from the iterable.

>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8]

It also changes the data of exisiting list in-place rather than returning a new list.

[*a, *b] unpacking method

Additional unpacking like * for iterable unpacking operator and ** for dictionary unpacking operator are extened from Python 3.5 as explained in PEP-0448.

>>> list1 = [1, 2, 3, 4]
>>> list2 = [5, 6, 7, 8]
>>> result = [*list1, list2]
>>> result
[1, 2, 3, 4, 5, 6, 7, 8]

This method couldn’t be applicable to the case of N lists unless you would like to unpack each list manually.

Warning

Iterable unpacking cannot be used in comprehension, as demostrated below.

>>> A = [1,2,3]
>>> B = [4,5,6]
>>> C = [7,8,9]
>>> [*t for t in [A,B,C]]
SyntaxError: iterable unpacking cannot be used in comprehension

Conclusion

Version In-place?
a + b - No
list(intertools.chain(a,b)) >=2.3 No
[*a, *b] >=3.5 No
a += b - Yes
a.extend(b) - Yes

We use perfplot module to comapare the performance of above methods.

Python List Concatenation Methods Performance Comparision

As shown in the graph, a.extend(b) and a+b methods are almost the same in the performance and the best among all the methods. list(chain(a,b)) method has the worst performance.