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
a + bjoins the two lists, but 3 and 4 appear twice. That is not a union.set(a) | set(b)makes a set of every item in either list. A set stores each value once.- A set has no fixed order, so
sorted()turns it into a list in ascending order.
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.