All Posts

Merge Lists in Python

Merge Lists in Python

To merge multiple lists in Python, you can use several methods depending on your requirements. In this tutorial, you will learn how to merge two or more lists.

Some of the methods to merge lists are as follows:

Using `+` (Concatenation Operator)


list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list1 + list2
print(merged_list)
    

Output:

[1, 2, 3, 4, 5, 6]

Using `extend()` Method

Merging lists using the extend() method:


list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1)
    

Output:

[1, 2, 3, 4, 5, 6]

Merge Lists Python Program

Using `itertools.chain()`


import itertools

list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = list(itertools.chain(list1, list2))
print(merged_list)
    

Output:

[1, 2, 3, 4, 5, 6]

Using List Comprehension


list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = [item for sublist in [list1, list2] for item in sublist]
print(merged_list)
    

Output:

[1, 2, 3, 4, 5, 6]

Using `*` Unpacking (Python 3.5+)


list1 = [1, 2, 3]
list2 = [4, 5, 6]
merged_list = [*list1, *list2]
print(merged_list)
    

Output:

[1, 2, 3, 4, 5, 6]


Python Tutorials

Python Tutorial on this website can be found at: