Computer >> Computer tutorials >  >> Programming >> Python

How does concatenation operator work on list in Python?


The concatenation operator creates a new list in Python using the initial lists in the order they were added in. This is not an inplace operation. 

example

list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = list1 + list2
print(list3)

Output

This will give the output −

[1, 2, 3, 'a', 'b']

There are other ways to concatenate 2 lists. Easiest is to use the extend function, if you want to extend the list in place. 

example

list1 = [1, 2, 3]
list2 = ['a', 'b']
list1.extend(list2)
print(list1)

Output

This will give the output −

[1, 2, 3, 'a', 'b']

You can also use unpacking operator * to create list from 2 lists. This can be used only in Python 3.5+.

Example

list1 = [1, 2, 3]
list2 = ['a', 'b']
list3 = [*list1, *list2]
print(list3)

Output

This will give the output −

[1, 2, 3, 'a', 'b']