Python Set union() Method
In this tutorial, we will understand about the python set union() method and its uses.
Python Set union() Method
The Python set union() method returns a new set containing all unique elements from all sets. It can also be written using the | operator. |
The syntax of the union() method is:
1
2
3
set.union(set2, set3, ...)
# or
set1 | set2 | set3
Python set union() Parameters
The union() method takes one or more parameters:
- set2, set3, …: Other sets or iterables to combine with the original set.
Here are examples demonstrating the union() method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Example 1: Basic union
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result) # Output: {1, 2, 3, 4, 5}
# Example 2: Using operator syntax
numbers1 = {1, 2}
numbers2 = {3, 4}
numbers3 = {5, 6}
result = numbers1 | numbers2 | numbers3
print(result) # Output: {1, 2, 3, 4, 5, 6}
# Example 3: Union with different iterables
set1 = {1, 2, 3}
list1 = [3, 4, 5]
tuple1 = (5, 6, 7)
result = set1.union(list1, tuple1)
print(result) # Output: {1, 2, 3, 4, 5, 6, 7}
The union() method is useful for combining multiple sets into one.
This post is licensed under CC BY 4.0 by the author.