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.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

8 lines
Python 3.9+
def 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

stdout
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

  1. Use `list(dict.fromkeys(list1 + list2))` to preserve the order of first occurrence.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.