Python Set Methods
Python provides several built-in methods to work with sets effectively. Below are commonly used set methods with explanation and examples.
Python कई built-in set methods देता है जिनसे हम sets पर आसानी से operations कर सकते हैं। नीचे सभी important methods के examples दिए गए हैं।
1. add() - Add single item
myset = {'apple', 'banana'}
myset.add('cherry')
print(myset)
Output:
{'banana', 'apple', 'cherry'}
Adds one element to the set.
Set में एक नया item जोड़ता है।
2. update() - Add multiple items
myset = {'apple'}
myset.update(['banana', 'cherry'])
print(myset)
Output:
{'banana', 'apple', 'cherry'}
Adds multiple elements from list/tuple/set to set.
List, Tuple, Set के elements को जोड़ता है।
3. remove() - Remove item (raises error if not found)
myset = {'apple', 'banana'}
myset.remove('banana')
print(myset)
Output:
{'apple'}
Removes specified element. Gives error if not present.
Item हटाता है। अगर item नहीं मिला तो error देता है।
4. discard() - Remove item (no error if not found)
myset = {'apple', 'banana'}
myset.discard('banana')
print(myset)
Output:
{'apple'}
Same as remove() but no error if item not found.
Item को हटाता है, लेकिन अगर नहीं मिला तो error नहीं देता।
5. pop() - Removes random item
myset = {'apple', 'banana', 'cherry'}
item = myset.pop()
print(item)
print(myset)
Output:
banana {'apple', 'cherry'} (output may vary)
Removes and returns a random item.
Random item को हटाकर return करता है।
6. clear() - Empty the set
myset = {'apple', 'banana'}
myset.clear()
print(myset)
Output:
set()
Empties the entire set.
Set को पूरी तरह खाली कर देता है।
7. copy() - Copy the set
set1 = {'apple', 'banana'}
set2 = set1.copy()
print(set2)
Output:
{'apple', 'banana'}
Creates a shallow copy of the set.
Set की shallow copy बनाता है।