Python Update Sets | How to Update a Set in Python

Python Update Sets

In Python, you can update a set by adding elements from another iterable (like another set, list, tuple, or string) using the update() method. You can also add a single element using add(). Updating a set means adding new unique elements to it.

Python में set को update करने का मतलब होता है उसमें नए unique elements जोड़ना। इसके लिए आप update() method से दूसरे iterable जैसे set, list, tuple या string के elements जोड़ सकते हैं। एक element जोड़ने के लिए add() method का उपयोग होता है।

Example 1: Update set with another set
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1)

Adds all elements from set2 into set1. Duplicate element '3' is only stored once.

set2 के सभी elements set1 में जोड़ दिए जाते हैं। '3' duplicate होने के कारण केवल एक बार रखा जाता है।

Output:

{1, 2, 3, 4, 5}
Example 2: Update set with list
set1 = {'apple', 'banana'}
list1 = ['banana', 'cherry', 'date']
set1.update(list1)
print(set1)

Adds elements from list to the set. Only unique elements remain.

List के elements set में जोड़े जाते हैं। केवल unique elements रहेंगे।

Output:

{'apple', 'banana', 'cherry', 'date'}
Example 3: Update set with string
set1 = {'a', 'b'}
set1.update('abc')
print(set1)

String is treated as iterable of characters and each character is added to set.

String को characters के iterable के रूप में treat किया जाता है और हर character set में जोड़ा जाता है।

Output:

{'a', 'b', 'c'}
Example 4: Add single element to set
set1 = {1, 2, 3}
set1.add(4)
print(set1)

Adds a single element to the set using add() method.

add() method से set में एक single element जोड़ा जाता है।

Output:

{1, 2, 3, 4}
Example 5: Update set with multiple iterables
set1 = {1, 2}
set1.update([3, 4], (4, 5), {5, 6})
print(set1)

update() can take multiple iterables and add all unique elements from them.

update() method एक से ज्यादा iterables ले सकता है और उनके unique elements जोड़ता है।

Output:

{1, 2, 3, 4, 5, 6}
Example 6: Updating with empty iterable
set1 = {1, 2, 3}
set1.update([])
print(set1)

Updating with an empty iterable does not change the set.

खाली iterable से update करने पर set में कोई बदलाव नहीं होता।

Output:

{1, 2, 3}