PythonMastery
Python programs · Lists · beginner

Union of two lists in Python

Combine two lists in Python so that every item appears once, with the set | operator or with dict.fromkeys() to keep the order.

The union of two lists is every item that is in either list, with each item only once.

The program

python
a = [1, 2, 3, 4]
b = [3, 4, 5, 6]

print("a + b:", a + b)
print("Union:", sorted(set(a) | set(b)))
output
a + b: [1, 2, 3, 4, 3, 4, 5, 6]
Union: [1, 2, 3, 4, 5, 6]

How it works

Keeping the original order

When the order matters (for example, the order people signed up), join the lists and then remove duplicates with dict.fromkeys(). It keeps the first time each item appears:

python
monday = ["Ada", "Linus", "Grace"]
tuesday = ["Grace", "Hedy", "Ada", "Alan"]

everyone = list(dict.fromkeys(monday + tuesday))
print(everyone)
output
['Ada', 'Linus', 'Grace', 'Hedy', 'Alan']

This works because a dictionary cannot have the same key twice, and it keeps keys in the order they were added.

Related programs: Set operations.

Learn the idea: Lists & Sequences, Sets: Unordered, Unique, Lightning Fast