Python Set Methods | Complete Guide with Examples

Python Set Methods

Python sets have several built-in methods to add, remove, copy, and perform other useful operations on sets. Let's explore these methods with clear examples and Hindi-English explanations.

Python sets में कई built-in methods होते हैं जो sets में elements जोड़ने, हटाने, कॉपी करने और अन्य उपयोगी operations करने के लिए होते हैं। आइए इन methods को साफ उदाहरणों और हिंदी-अंग्रेज़ी explanations के साथ समझते हैं।

add() - Add a single element to the set
s = {1, 2, 3}
s.add(4)
print(s)

Adds the element 4 to the set. If element already exists, set remains unchanged.

set में element 4 जोड़ता है। अगर element पहले से हो तो set में कोई बदलाव नहीं होता।

Output:

{1, 2, 3, 4}
update() - Add multiple elements from iterable
s = {1, 2}
s.update([3, 4, 5])
print(s)

Adds multiple elements from list to the set. You can pass any iterable like list, tuple, or set.

list के multiple elements set में जोड़ता है। कोई भी iterable पास किया जा सकता है।

Output:

{1, 2, 3, 4, 5}
remove() - Remove an element (raises error if not found)
s = {1, 2, 3}
s.remove(2)
print(s)

Removes element 2 from set. If element is not found, raises KeyError.

set से element 2 हटाता है। अगर element नहीं मिले तो error देता है।

Output:

{1, 3}
discard() - Remove an element (no error if not found)
s = {1, 2, 3}
s.discard(4)
print(s)

Removes element 4 if present. Does nothing if element not found, no error raised.

अगर element set में हो तो हटाता है। नहीं होने पर कुछ नहीं करता, error नहीं देता।

Output:

{1, 2, 3}
pop() - Remove and return an arbitrary element
s = {1, 2, 3}
element = s.pop()
print(element)
print(s)

Removes and returns a random element from set. Set size decreases by one.

set से कोई भी एक element हटाता और वापस देता है। set का size कम हो जाता है।

Output:

1
{2, 3}
(Note: popped element may vary)
clear() - Remove all elements from the set
s = {1, 2, 3}
s.clear()
print(s)

Removes all elements, making the set empty.

set के सारे elements हटाता है, set खाली हो जाता है।

Output:

set()
copy() - Return a shallow copy of the set
s1 = {1, 2, 3}
s2 = s1.copy()
print(s2)
s2.add(4)
print(s1)
print(s2)

Creates a shallow copy of set. Changes to the copy do not affect the original set.

set की shallow copy बनाता है। copy में बदलाव original set को प्रभावित नहीं करता।

Output:

{1, 2, 3}
{1, 2, 3}
{1, 2, 3, 4}