Join Two Sets In One Line Without Using “|” in Python
Last Updated :
30 Jan, 2024
In this article, we will understand how to join two sets in one line without using “|”.As we know when working with sets in Python, there might be scenarios where you need to combine two sets into a single set. The easiest way to achieve this is by using the union operator (|). However, we need to join two sets in one line without using “|”. So in this article, we will explore different methods to join two sets without using the | operator.
How To Join Two Sets In One Line Without Using “|”?
Below, are the ways through which we can Join Two Sets In One Line Without Using “|” in Python.
Join Two Sets In One Line Using set()
Method
In this example, the below code combines two sets, set1 and set2, by converting them to lists, extending one list with the other, and then converting the result back into a set using the `set()` function. The resulting set, contains elements from both original sets.
Python3
set1 = { 1 , 2 , 3 }
set2 = { 3 , 4 , 5 }
result_set = set ( list (set1) + list (set2))
print (result_set)
|
Join Two Sets In One Line Using update()
Method
In this example, below code utilizes the `update()` method to merge elements from set2 into set1, effectively joining the two sets. The resulting set, now containing elements from both original sets, is displayed using the `print()` function.
Python3
set1 = { 1 , 2 , 3 }
set2 = { 3 , 4 , 5 }
set1.update(set2)
print (set1)
|
Join Two Sets In One Line Using the *
operator
In this example, below code employs the * operator to unpack elements from both sets, creating a new set using the set() constructor. The resulting set, containing elements from both original sets, is stored in the variable “result_set” and printed.
Python3
set1 = { 1 , 2 , 3 }
set2 = { 3 , 4 , 5 }
result_set = set (( * set1, * set2))
print (result_set)
|
Join Two Sets In One Line Using itertools.chain()
Method
In this example, below code utilizes the `itertools.chain()` function to concatenate elements from both sets, and then a new set is created using the set() constructor. The resulting set, containing elements from both original sets, is stored in the variable “result_set” and printed.
Python3
from itertools import chain
set1 = { 1 , 2 , 3 }
set2 = { 3 , 4 , 5 }
result_set = set (chain(set1, set2))
print (result_set)
|
Conclusion
In conclusion, when seeking to join two sets in Python without using the union operator (|), several methods offer concise and efficient solutions. Whether through list conversion and set creation, leveraging set methods like update()
or symmetric_difference()
, or using itertools.chain()
, these alternatives provide flexibility and clarity for combining sets in a single line of code. Choosing the appropriate method depends on the specific requirements of the task at hand, offering diverse approaches for set manipulation in Python.
Share your thoughts in the comments
Please Login to comment...