B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP Update Sets in Python with Examples | LiveCodeProgramming
LiveCodeProgramming

Update Sets in Python

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 जोड़ सकते हैं।

1. Using update() method

Adds 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'}
2. Using union() to return new set

Returns 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'}
3. Using update() with list or tuple
fruits = {"apple"}
more = ["banana", "cherry"]
fruits.update(more)
print(fruits)
Output:
{'apple', 'banana', 'cherry'}
4. Set Unpacking with *

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'}
5. Using for loop

You 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'}