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:

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:

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:

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:

Similar Reads