Python - Join Lists


In Python, List is classified as a sequence type object. It is a collection of items, which may be of different data types, with each item having a positional index starting with 0. You can use different ways to join two Python lists.

All the sequence type objects support concatenation operator, with which two lists can be joined.

L1 = [10,20,30,40]
L2 = ['one', 'two', 'three', 'four']
L3 = L1+L2
print ("Joined list:", L3)

It will produce the following output

Joined list: [10, 20, 30, 40, 'one', 'two', 'three', 'four']

You can also use the augmented concatenation operator with "+=" symbol to append L2 to L1

L1 = [10,20,30,40]
L2 = ['one', 'two', 'three', 'four']
L1+=L2
print ("Joined list:", L1)

The same result can be obtained by using the extend() method. Here, we need to extend L1 so as to add elements from L2 in it.

L1 = [10,20,30,40]
L2 = ['one', 'two', 'three', 'four']
L1.extend(L2)
print ("Joined list:", L1)

To add items from one list to another, a classical iterative solution also works. Traverse items of second list with a for loop, and append each item in the first.

L1 = [10,20,30,40]
L2 = ['one', 'two', 'three', 'four']

for x in L2:
   L1.append(x)
   
print ("Joined list:", L1)

A slightly complex approach for merging two lists is using list comprehension, as following code shows −

L1 = [10,20,30,40]
L2 = ['one', 'two', 'three', 'four']
L3 = [y for x in [L1, L2] for y in x]
print ("Joined list:", L3)
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements