To update a set in Python (i.e., add multiple elements), you can use several methods like update()
, union()
, and unpacking with *
. These methods help you combine sets or add iterable elements.
Python में set को update करने के लिए हम update()
, union()
, या unpacking जैसे तरीकों का इस्तेमाल करते हैं जिससे आप multiple items जोड़ सकते हैं।
update()
methodAdds elements from another set or any iterable (like list/tuple).
दूसरे set या iterable से items जोड़ने के लिए उपयोग होता है।
set1 = {"apple", "banana"}
set2 = {"cherry", "mango"}
set1.update(set2)
print(set1)
Output:
{'apple', 'banana', 'cherry', 'mango'}
union()
to return new setReturns a new set with elements from both sets. Doesn't modify original set.
दोनों sets को जोड़कर नया set बनाता है। पुराना set नहीं बदलता।
set1 = {"apple", "banana"}
set2 = {"mango", "cherry"}
new_set = set1.union(set2)
print(new_set)
Output:
{'apple', 'banana', 'mango', 'cherry'}
update()
with list or tuplefruits = {"apple"}
more = ["banana", "cherry"]
fruits.update(more)
print(fruits)
Output:
{'apple', 'banana', 'cherry'}
*
You can merge multiple sets using *
unpacking into a new set.
Multiple sets को *
से unpack कर नया set बना सकते हैं।
a = {"A", "B"}
b = {"C", "D"}
c = {"E"}
merged = {*a, *b, *c}
print(merged)
Output:
{'A', 'B', 'C', 'D', 'E'}
for
loopYou can also loop through items to add them individually.
आप manually items जोड़ने के लिए loop का उपयोग कर सकते हैं।
s = {"red"}
new_items = ["green", "blue"]
for item in new_items:
s.add(item)
print(s)
Output:
{'red', 'green', 'blue'}