How to Get the Union of Two Lists Without Duplicates in Python
Merge two lists and remove duplicate values using a set, then convert back to a list.
Python code
8 linesdef union_without_duplicates(list1, list2):
return list(set(list1 + list2))
if __name__ == "__main__":
list_a = [1, 2, 3, 4]
list_b = [3, 4, 5, 6]
result = union_without_duplicates(list_a, list_b)
print(f"Union of {list_a} and {list_b}: {result}")
Output
Union of [1, 2, 3, 4] and [3, 4, 5, 6]: [1, 2, 3, 4, 5, 6]
How it works
The list1 + list2 operation concatenates the two input lists into a single list that may contain duplicates. Wrapping this combined list in set() removes all duplicate occurrences because a set is an unordered collection of unique elements. Finally, list() converts the set back to a list, giving you a union of both lists with distinct values. Note that the order of elements in the resulting list is not guaranteed; if you need to preserve the original order, you should use a loop or dict.fromkeys() instead.
Common mistakes
- Assuming the set conversion preserves the original order of elements.
- Forgetting to convert the set back to a list, returning a set object instead.
- Using `list(set(list1 + list2))` when the inputs are not lists (e.g., tuples or generators), which still works but may be less clear.
- Not considering that this approach only works with hashable elements; unhashable elements like lists or dicts raise a TypeError.
Variations
- Use `list(dict.fromkeys(list1 + list2))` to preserve the order of first occurrence.
- Use `list(set(list1) | set(list2))` for the set union operation, which also removes duplicates.
Real-world use cases
- Combining two customer email lists in a marketing tool while removing duplicate contacts before sending a campaign.
- Merging two configuration file paths or environment variable lists to get a unique set of directories to search.
- In a data processing pipeline, merging two columns of ID values from different sources to create a unique set of records for a report.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.