Python merge two lists without duplicates | Example code

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 an 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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.