There are different ways to merge two lists in python. According to our python version and packages installed, we can use any one of them to merge two lists.

How to merge two lists in Python:

Example
#Input
list1 = [10, 20, 30]
list2 = [40, 50, 60]
#Output
[10, 20, 30, 40, 50, 60]

1. Merging two Lists in Python:

We can simply merge two lists using + operator like below.

list1 = [10, 20, 30]
list2 = [40, 50, 60]
merged_list = list1+list2

print("Merged List: ",merged_list)

#It is also equivalent to above code using +=

list1 += list2
print("Merged List using +=: ",list1)

The above solution internally creates a new list (merged_list) with a shallow copy of list1 and is concatenated with a shallow copy of list2.

Output:

Terminal
Merged List:  [10, 20, 30, 40, 50, 60]
Merged List using +=: [10, 20, 30, 40, 50, 60]

2. Merge two Lists in Python using PEP:

If you are using python >= 3.5 version the PEP additional unpacking generations allows you to concatenate lists using * operator.

list1 = [10, 20, 30]
list2 = [40, 50, 60]

mergedList = [*list1, *list2]
print(mergedList)

Output:

Terminal
[10, 20, 30, 40, 50, 60]

3. Merge two Lists in Python using chain:

The itertools allows us to chain the multiple lists so that the simple solution is to iterating the items in both the lists and generate a new list (or we can even use for processing).

import itertools

list1 = [10, 20, 30]
list2 = [40, 50, 60]

for item in itertools.chain(list1, list2):
    print(item)

Output:

Terminal
10
20
30
40
50
60

4. Merge two Lists in Python using list:

As we know, the list allows duplicate items. So if we wanted to remove duplicates while merging two lists, we could use the below solution.

list1 = [10, 20, 30, 40]
list2 = [30, 40, 50, 60]

merged_list = list(set(list1+list2))
print("Merged List with out duplicates: ",merged_list)
Note: As we are converting lists to set it will lose the order of elements.

Output:

Terminal
Merged List with out duplicates:  [40, 10, 50, 20, 60, 30]

5. Merge two Lists in Python using Extend:

We can even extend the list by appending another list using the list.extend().

list1 = [10, 20, 30, 40]
list2 = [30, 40, 50, 60]

list1.extend(list2)
print(list1)

Output:

Terminal
[10, 20, 30, 40, 30, 40, 50, 60]

References:

Happy Learning 🙂