Python concatenation list

Concatenating Lists in Python

In Python, a list is classified as a sequence-type object. It is a collection of items of different data types, each with a zero-based index. You can use different methods to concatenate two Python lists.

All sequence-type objects support the concatenation operator, which allows you to concatenate two lists.

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 enhanced concatenation operator “+=” to append L2 to L1

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

We can also achieve the same result by using the extend() method. Here, we extend L1 to add the elements from L2.

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, we can also use a classic iterative solution. Use a for loop to iterate over the items in the second list and append each item to 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 more complex way to use list comprehensions is to merge two lists, as shown below −

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)

Leave a Reply

Your email address will not be published. Required fields are marked *