Python
lists
union
programming
coding tips

Simplest way to form a union of two lists

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The simplest way to form a union of two Python lists depends on what you mean by “union.” If you want unique elements regardless of order, sets are the cleanest answer. If you need uniqueness while preserving the first-seen order, you need a slightly different approach.

Set Union for Unique Values

In mathematics, a union removes duplicates. Python sets model that behavior directly, so the shortest solution is to convert both lists to sets and combine them.

python
1a = [1, 2, 3, 3]
2b = [3, 4, 5]
3
4result = list(set(a) | set(b))
5print(result)

You can also use the union method:

python
1a = [1, 2, 3]
2b = [3, 4, 5]
3
4result = list(set(a).union(b))
5print(result)

Both versions remove duplicates. The tradeoff is that sets do not preserve the original list order, so the resulting list may come out in an order that looks arbitrary.

Preserve Order While Removing Duplicates

If order matters, a common pattern is to concatenate the lists and then use dict.fromkeys. Since Python dictionaries preserve insertion order, the first occurrence of each item is retained.

python
1a = ['red', 'blue', 'green']
2b = ['blue', 'yellow', 'red']
3
4result = list(dict.fromkeys(a + b))
5print(result)

Output:

python
['red', 'blue', 'green', 'yellow']

This is often the most practical answer in application code because it produces predictable results without writing a manual loop.

Manual Loop When You Need Control

A loop is longer, but it becomes useful when equality rules are more complicated than Python's default behavior. For example, you might want case-insensitive deduplication or custom normalization.

python
1a = ['Alice', 'bob']
2b = ['BOB', 'carol']
3
4result = []
5seen = set()
6
7for name in a + b:
8    key = name.lower()
9    if key not in seen:
10        seen.add(key)
11        result.append(name)
12
13print(result)

That produces a union based on lowercase comparison while preserving the first spelling encountered.

When the Elements Are Unhashable

Set-based solutions only work for hashable values. Lists and dictionaries are unhashable, so this will fail:

python
1items1 = [[1, 2], [3, 4]]
2items2 = [[3, 4], [5, 6]]
3
4# TypeError: unhashable type: 'list'
5# result = list(set(items1) | set(items2))

For nested lists or other unhashable structures, use a manual membership check:

python
1items1 = [[1, 2], [3, 4]]
2items2 = [[3, 4], [5, 6]]
3
4result = []
5for item in items1 + items2:
6    if item not in result:
7        result.append(item)
8
9print(result)

This is slower for large collections because item not in result is a linear search, but it works with values that sets cannot store.

Performance Considerations

For large lists of hashable items, set-based union is typically the fastest option because membership checks in a set are near constant time on average.

python
1def union_with_sets(a, b):
2    return list(set(a) | set(b))
3
4
5def union_preserve_order(a, b):
6    return list(dict.fromkeys(a + b))

Both functions are efficient for ordinary Python values such as integers, strings, and tuples. Choose between them based on whether output order matters.

Choosing the Right Definition

Many questions about list union are really about requirements, not syntax. Ask these before picking an implementation:

  • Do duplicates need to be removed?
  • Must the result preserve order?
  • Are the items hashable?
  • Do you want exact equality or custom matching rules?

Once those answers are clear, the implementation becomes straightforward.

Common Pitfalls

The most common mistake is assuming set(a) | set(b) preserves order. It does not. If stable order matters, use dict.fromkeys(a + b) or a custom loop.

Another problem is using set union with unhashable elements such as lists or dictionaries. Python raises a TypeError because those values cannot be inserted into a set.

A third mistake is using the word “union” when you actually want concatenation. If duplicates should remain, then a + b is not a union in the set-theoretic sense; it is just list concatenation.

Summary

  • For hashable items where order does not matter, use list(set(a) | set(b)).
  • For hashable items where order does matter, use list(dict.fromkeys(a + b)).
  • For unhashable items, use a manual loop and membership checks.
  • Be explicit about whether you want mathematical union or simple concatenation.
  • Pick the method based on data type, ordering requirements, and performance needs.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.