Merge Two Lists Without Duplicates Python (original) (raw)
Last Updated : 08 Feb, 2025
We are given two lists containing elements and our task is to merge them into a single list while ensuring there are no duplicate values. **For example: a = [1, 2, 3, 4] and b = [3, 4, 5, 6] then the merged list should be: [1, 2, 3, 4, 5, 6]
Using set()
set() function automatically removes duplicates making it the most efficient way to merge two lists while keeping only unique elements.
Python `
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
res = list(set(a + b))
print(res)
`
**Explanation:
- a + b merges both lists and set(a + b) removes duplicates.
- list(set(...)) converts the set back into a list.
Using Dictionary Keys (dict.fromkeys())
Since dictionary keys are unique, we can use dict.fromkeys() to remove duplicates while preserving the order of elements.
Python `
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
res = list(dict.fromkeys(a + b))
print(res)
`
**Explanation:
- a + b merges both lists and dict.fromkeys(a + b) creates a dictionary where keys are the merged elements (removing duplicates).
- list(...) converts the dictionary keys back into a list preserving order.
Using a for Loop
We can manually iterate through both lists and add elements to a new list only if they are not already present.
Python `
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
res = []
for x in a + b:
if x not in res:
res.append(x)
print(res)
`
**Explanation:
- We initialize an empty list result and iterate through a + b, check if x is already in result.
- If x is not in result then only we append it.
Using List Comprehension with set
This method combines a set for fast lookups with a list comprehension to preserve order efficiently.
Python `
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]
seen = set()
res = [x for x in a + b if x not in seen and not seen.add(x)]
print(res)
`
**Explanation:
- We initialize an empty set() called seen to track unique elements.
- We iterate through a + b using list comprehension and if x is not in seen then it is added to result, seen.add(x) adds x to seen ensuring duplicates are ignored.