Python Program to Find Union of Two Lists
union() method or the | operator like this: union_list = list(set(list1) | set(list2)).Examples
How to Think About It
Algorithm
Code
list1 = [1, 2, 3] list2 = [3, 4, 5] union_list = list(set(list1) | set(list2)) print(union_list)
Dry Run
Let's trace the example lists [1, 2, 3] and [3, 4, 5] through the code.
Convert lists to sets
set(list1) = {1, 2, 3}, set(list2) = {3, 4, 5}
Find union of sets
set(list1) | set(list2) = {1, 2, 3, 4, 5}
Convert union set to list
list({1, 2, 3, 4, 5}) = [1, 2, 3, 4, 5]
Print the result
Output: [1, 2, 3, 4, 5]
| Operation | Value |
|---|---|
| set(list1) | {1, 2, 3} |
| set(list2) | {3, 4, 5} |
| Union | {1, 2, 3, 4, 5} |
| Final list | [1, 2, 3, 4, 5] |
Why This Works
Step 1: Convert lists to sets
Using set() removes duplicate elements from each list, so we only keep unique items.
Step 2: Find union of sets
The | operator combines both sets, keeping only one copy of each unique element.
Step 3: Convert back to list
We convert the set back to a list because sets are unordered and lists are easier to use for most tasks.
Alternative Approaches
list1 = [1, 2, 3] list2 = [3, 4, 5] union_list = list(set(list1).union(set(list2))) print(union_list)
list1 = [1, 2, 3] list2 = [3, 4, 5] union_list = list1.copy() for item in list2: if item not in union_list: union_list.append(item) print(union_list)
Complexity: O(n + m) time, O(n + m) space
Time Complexity
Converting lists to sets takes O(n) and O(m) time, where n and m are the lengths of the lists. The union operation also takes O(n + m). Overall, the time is linear in total input size.
Space Complexity
Extra space is needed to store the sets and the union, which is O(n + m) in the worst case when all elements are unique.
Which Approach is Fastest?
Using sets with the | operator or union() method is fastest and simplest. The loop method is slower due to repeated membership checks.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set union with | operator | O(n + m) | O(n + m) | Fastest and simplest for unique elements |
| Set union() method | O(n + m) | O(n + m) | Same as | operator, more explicit |
| Loop with membership check | O(n * m) | O(n + m) | Maintains order but slower for large lists |