Python merge two lists without duplicates
Published on Aug. 22, 2023, 12:16 p.m.
To merge two lists in Python without duplicates, you can convert them to sets and then use the union operator |
to combine them. Like this:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
result = list(set(list1) | set(list2))
print(result) # Output: [1, 2, 3, 4, 5, 6]
In this example, we first convert both lists to sets (which remove duplicates) using the set()
function. We then combine these sets using the union operator |
to create a new set that only contains unique elements. Finally, we convert this result set back to a list using the list()
function.
Alternatively, you could use the extend()
method to combine the lists and then convert them to a set to remove duplicates:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
result = list(set(list1.extend(list2)))
print(result) # Output: [1, 2, 3, 4, 5, 6]
In this example, we first use the extend()
method on list1
to add the elements of list2
to it. We then convert the combined list to a set using the set()
function to remove any duplicates, and finally convert that set back to a list using the list()
function.