How to find the union of two lists in Python
How to find the union of two lists in Python.
Here's a step-by-step tutorial on how to find the union of two lists in Python.
- First, let's create two lists that we want to find the union of. For this example, let's assume we have the following lists:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
- To find the union of these two lists, we can use the
union
operator (|
) in Python. However, before we can use it, we need to convert our lists into sets.
set1 = set(list1)
set2 = set(list2)
Converting the lists to sets allows us to take advantage of the set operations, such as finding the union.
- Now that we have the sets, we can find the union by using the
union
operator (|
). This operator combines the elements of both sets, removing any duplicates.
union_set = set1 | set2
The resulting union_set
will contain all the unique elements from both set1
and set2
.
- If you want to convert the resulting set back to a list, you can use the
list()
function.
union_list = list(union_set)
The union_list
will now contain the union of the two original lists.
Here's the complete code:
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
set1 = set(list1)
set2 = set(list2)
union_set = set1 | set2
union_list = list(union_set)
print(union_list)
Output:
[1, 2, 3, 4, 5, 6]
In this example, the union of list1
and list2
is [1, 2, 3, 4, 5, 6]
.