Python Program to Find Union of Lists
| operator or set.union(), then converting back to a list like 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 where list1 = [1, 2, 3] and list2 = [3, 4, 5] through the code.
Convert lists to sets
set(list1) = {1, 2, 3}, set(list2) = {3, 4, 5}
Find union of sets
{1, 2, 3} | {3, 4, 5} = {1, 2, 3, 4, 5}
Convert union set back 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, making it easier to combine unique items.
Step 2: Use union operation
The | operator or set.union() combines two sets to include all unique elements from both.
Step 3: Convert back to list
Since the original data type is a list, converting the set back to a list gives the final union result in list form.
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 and performing union takes linear time relative to the total number of elements in both lists.
Space Complexity
Extra space is used to store sets and the resulting union list, proportional to the combined size of input lists.
Which Approach is Fastest?
Using set union is fastest and simplest; looping to check membership 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 union |
| Set union() method | O(n + m) | O(n + m) | Same as | operator, more explicit |
| Loop with membership check | O(n * m) | O(n + m) | Preserving order but slower for large lists |
+ operator without removing duplicates, which keeps repeated items.