Python Join Sets
In Python, "joining" sets means combining two or more sets to get a new set containing all unique elements from all sets. Python provides multiple ways to join sets, such as using the union()
method, the |
operator, and the update()
method.
Python में sets को join करने का मतलब होता है दो या दो से अधिक sets को मिलाकर एक नया set बनाना, जिसमें सभी sets के unique elements हों। Python में sets join करने के कई तरीके हैं, जैसे union()
method, |
operator, और update()
method।
Example 1: Using union() method
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result)
The union() method returns a new set with all unique elements from both sets. Original sets remain unchanged.
union() method दोनों sets के unique elements से नया set बनाता है। मूल sets अपरिवर्तित रहते हैं।
Output:
Example 2: Using | operator
set1 = {'a', 'b'}
set2 = {'b', 'c'}
result = set1 | set2
print(result)
The | operator performs union of two sets and returns a new set.
| operator दो sets का union करता है और नया set लौटाता है।
Output:
Example 3: Using update() method
set1 = {1, 2, 3}
set2 = {4, 5}
set1.update(set2)
print(set1)
The update() method adds all elements from set2 into set1. This modifies set1 in place and returns None.
update() method set2 के elements set1 में जोड़ देता है। set1 को सीधे modify करता है।
Output:
Example 4: Joining multiple sets with union()
set1 = {1, 2}
set2 = {3, 4}
set3 = {4, 5}
result = set1.union(set2, set3)
print(result)
union() can take multiple sets as arguments and returns a new set with all unique elements.
union() method एक से अधिक sets को argument के रूप में ले सकता है और सभी unique elements वाला नया set बनाता है।
Output:
Example 5: Using |= operator (in-place union)
set1 = {'x', 'y'}
set2 = {'y', 'z'}
set1 |= set2
print(set1)
The |= operator performs union and updates the set on the left in-place.
|= operator union करता है और बाईं set को inplace update करता है।
Output: