Skip to content

Python merge two lists without duplicates | Example code

  • by

Python merges two lists without duplicates could be accomplished by using a set. And use the + operator to merge it.

list(set(list1 + list2))

Python merge list without duplicates example

Simple example code using set with + operator.

a = ['hello', 'world']
b = ['hello', 'universe']

unique = list(set(a + b))

print(unique)

Output:

Python merge two lists without duplicates

Another method uses NumPy

You have to import a NumPy module for it.

import numpy as np

list1 = [1, 2, 2, 5]

list2 = [2, 5, 7, 9]

res = np.unique(list1 + list2)
print(res)

Output: [1 2 5 7 9]

Combining two lists and without duplicates and don’t remove duplicates in the original list

Use set to remove duplicate without removing element from the original list.

list1 = [1, 2, 2, 5]

list2 = [2, 5, 7, 9]

res = list(set(list1 + list2))

print(res)
print(list1)
print(list2)

Output:

[1, 2, 5, 7, 9]
[1, 2, 2, 5]
[2, 5, 7, 9]

You can do also convert the list to a new set.

set_1 = set(list_1)

set_2 = set(list_2)

Do comment if you have any questions or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading