Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

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)



The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Дали Ви помогна овој одговор? 1 Корисниците го најдоа ова како корисно (1 Гласови)