Published:
added on 06 July,2018
Lists in Python can be concatenated in two ways
Using + operator
Using extend
Let list_a and list_b be defined as below
list_a = [1, 2, 3, 4]
list_b = [5, 6, 7, 8]
Using + operator to concatenate two list_a and list_b
list_c = list_a + lis_b
print list_c # Output: [1, 2, 3, 4, 5, 6, 7, 8]
If we do not want new list i.e. list_c
list_a = list_a + list_b
print list_a # Output: [1, 2, 3, 4, 5, 6, 7, 8]
Using extend
Extend operator can be used to concatenate one list into another. It is not possible to store the value into the third list. One of the existing list has to store the concatenated result.
list_c = list_a.extend(list_b)
print list_c # Output: NoneType
print list_a # Output: [1, 2, 3, 4, 5, 6, 7, 8]
print list_b # Output: [5, 6, 7, 8]
In the above example, extends concatenates the list_b into list_a
Which is better?
We can use either of the ways to concatenate the list. There is not much difference in the performance. But as extends involves a function it is little bit more expensive that + operator. But this difference will be visible only when the concatenation is done very large number of times