Python Notes
Python Set के सभी built-in methods का complete reference – add, remove, discard, pop, clear, update, union, intersection, difference, symmetric_difference और in-place variants के साथ examples।
Quick Reference Table
| Method | Description | Returns | In-place? |
|---|---|---|---|
add(x) | Element add करे | None | ✅ |
remove(x) | Element हटाए (error if missing) | None | ✅ |
discard(x) | Element हटाए (no error if missing) | None | ✅ |
pop() | Random element हटाए व return करे | Element | ✅ |
clear() | सभी elements हटाए | None | ✅ |
copy() | Shallow copy return करे | Set | ❌ |
update(*others) | Multiple iterables से elements add करे | None | ✅ |
union(*others) | Union का new set return करे | Set | ❌ |
intersection(*others) | Intersection का new set | Set | ❌ |
intersection_update(*others) | In-place intersection | None | ✅ |
difference(*others) | Difference का new set | Set | ❌ |
difference_update(*others) | In-place difference | None | ✅ |
symmetric_difference(other) | Sym. diff. new set | Set | ❌ |
symmetric_difference_update(other) | In-place sym. diff. | None | ✅ |
issubset(other) | Subset check | bool | ❌ |
issuperset(other) | Superset check | bool | ❌ |
isdisjoint(other) | Disjoint check | bool | ❌ |
2. remove() vs discard() – Element हटाना
दोनों element हटाते हैं, लेकिन missing element पर different behavior:
s = {1, 2, 3, 4, 5}
# remove() – element not found → ValueError
s.remove(3)
print(s) # {1, 2, 4, 5}
try:
s.remove(99) # not in set!
except KeyError as e:
print(f"KeyError: {e}") # KeyError: 99
# discard() – element not found → silently ignored
s.discard(2)
print(s) # {1, 4, 5}
s.discard(99) # no error!
print(s) # {1, 4, 5} (unchanged)
# When to use which?
# remove() – जब sure हो element है, नहीं मिला तो error चाहिए
# discard() – जब sure नहीं, silently skip करना हो
# Safe remove pattern with remove():
def safe_remove(s, val):
if val in s:
s.remove(val)
safe_remove(s, 1)
print(s) # {4, 5}Output:
{1, 2, 4, 5}
KeyError: 99
{1, 4, 5}
{1, 4, 5}
{4, 5}
remove() vs discard() comparison
| Feature | remove(x) | discard(x) |
|---|---|---|
| x exists | Removes it | Removes it |
| x missing | Raises KeyError | No error |
| Returns | None | None |
| Use when | Element must exist | Optional element |
3. pop() – Random Element हटाना
Set से एक arbitrary (random) element हटाता और return करता है।
s = {10, 20, 30, 40, 50}
# pop() removes an arbitrary element
elem = s.pop()
print(f"Popped: {elem}")
print(f"Set: {s}")
# Pop all elements
while s:
print(s.pop(), end=" ")
print() # newline
# Empty set से pop → KeyError
try:
{}.pop() # empty set
except KeyError as e:
print(f"Error: {e}") # set is empty
# Safe pop
s = {1, 2, 3}
if s:
elem = s.pop()
print(f"Safely popped: {elem}")
# Note: Can't pop by index (sets are unordered)
# s.pop(0) → TypeErrorOutput:
| Popped | (some element - unpredictable) |
| Set | (remaining elements) |
| Error | 'pop from an empty set' |
| Safely popped | (some element) |
⚠️ Warning:pop()unpredictable है क्योंकि sets unordered हैं। जब specific element चाहिए,remove()याdiscard()use करें।
4. clear() – Set खाली करना
s = {1, 2, 3, 4, 5}
print(f"Before: {s}, len={len(s)}")
s.clear()
print(f"After: {s}, len={len(s)}") # set(), len=0
# clear() vs reassignment
a = {1, 2, 3}
b = a # same reference
a.clear() # modifies in-place
print(a) # set()
print(b) # set() ← b also empty!
# vs
a = {1, 2, 3}
b = a
a = set() # a points to new empty set
print(a) # set()
print(b) # {1, 2, 3} ← b unchanged!5. copy() – Shallow Copy
original = {1, 2, 3, 4, 5}
# copy() method
copy1 = original.copy()
copy2 = set(original) # alternative
# They are equal but not same object
print(copy1 == original) # True
print(copy1 is original) # False
# Modifying copy doesn't affect original
copy1.add(999)
print(original) # {1, 2, 3, 4, 5} ← unchanged
print(copy1) # {1, 2, 3, 4, 5, 999}
# Note: Sets contain only immutable (hashable) elements,
# so shallow copy is effectively a deep copy for simple sets6. update() – Multiple Sources से Add करना
update() एक या multiple iterables के सभी elements को add करता है। यह in-place union है।
Output:
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6, 7, 8}
{'a', 'b', 'c', 'd', 'e'}
{1, 2, 3, 4, 5, 6, 7, 8}
{1, 2, 3, 4, 5}
None
7. union() – Union (New Set)
8. intersection() and intersection_update()
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}
C = {4, 5, 8, 9}
# intersection() – new set
result = A.intersection(B)
print(result) # {3, 4, 5}
print(A) # {1, 2, 3, 4, 5} ← unchanged
# Multiple sets
result = A.intersection(B, C)
print(result) # {4, 5} (common in all three)
# Operator equivalent
print(A & B) # {3, 4, 5}
print(A & B & C) # {4, 5}
# intersection_update() – in-place
A = {1, 2, 3, 4, 5}
A.intersection_update(B)
print(A) # {3, 4, 5} ← A is now modified!
# Operator equivalent
A = {1, 2, 3, 4, 5}
A &= B
print(A) # {3, 4, 5}Output:
{3, 4, 5}
{1, 2, 3, 4, 5}
{4, 5}
{3, 4, 5}
{4, 5}
{3, 4, 5}
{3, 4, 5}
9. difference() and difference_update()
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}
C = {4, 8}
# difference() – new set (A में है, B में नहीं)
result = A.difference(B)
print(result) # {1, 2}
print(A) # unchanged
# Multiple sets difference (A - B - C)
result = A.difference(B, C)
print(result) # {1, 2}
# Operator equivalent
print(A - B) # {1, 2}
print(A - B - C) # {1, 2}
# Note direction matters
print(B - A) # {6, 7} (different result!)
# difference_update() – in-place
A = {1, 2, 3, 4, 5}
A.difference_update(B)
print(A) # {1, 2}
# Operator
A = {1, 2, 3, 4, 5}
A -= B
print(A) # {1, 2}10. symmetric_difference() and symmetric_difference_update()
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# symmetric_difference() – elements in exactly ONE set
result = A.symmetric_difference(B)
print(result) # {1, 2, 5, 6}
# Operator equivalent
print(A ^ B) # {1, 2, 5, 6}
# symmetric_difference_update() – in-place
A = {1, 2, 3, 4}
A.symmetric_difference_update(B)
print(A) # {1, 2, 5, 6}
# Operator
A = {1, 2, 3, 4}
A ^= B
print(A) # {1, 2, 5, 6}
# Practical use: find elements that changed
before = {"apple", "banana", "cherry"}
after = {"banana", "cherry", "date", "elderberry"}
added = after - before
removed = before - after
changed = before ^ after
print("Added:", added) # Added: {'date', 'elderberry'}
print("Removed:", removed) # Removed: {'apple'}
print("Changed:", changed) # Changed: {'apple', 'date', 'elderberry'}11. issubset(), issuperset(), isdisjoint()
12. Operator vs Method Comparison
| Operation | Operator | Method | Method accepts | |
|---|---|---|---|---|
| Union | `A \ | B` | A.union(B) | Any iterable |
| Intersection | A & B | A.intersection(B) | Any iterable | |
| Difference | A - B | A.difference(B) | Any iterable | |
| Sym. Diff | A ^ B | A.symmetric_difference(B) | Any iterable | |
| In-place Union | `A \ | = B` | A.update(B) | Any iterable |
| In-place Inter. | A &= B | A.intersection_update(B) | Any iterable | |
| In-place Diff. | A -= B | A.difference_update(B) | Any iterable | |
| In-place Sym. | A ^= B | A.symmetric_difference_update(B) | Set only | |
| Subset | A <= B | A.issubset(B) | Any iterable | |
| Superset | A >= B | A.issuperset(B) | Any iterable |
💡 Key Difference: Methods like.union(),.intersection()etc. accept any iterable (list, tuple, etc.), while operators (|,&) require both operands to be sets.
13. Interview Questions
Q1: remove() और discard() में क्या difference है?
remove(x)– element missing होने परKeyErrorraise करता है।discard(x)– element missing होने पर silently ignore करता है। Usediscardwhen you're not sure if element exists।
Q2: Set में pop() किस element को remove करता है?
Set unordered है, इसलिए pop() arbitrary (implementation-defined) element remove करता है। Order guaranteed नहीं है।Q3: update() और union() में क्या फर्क है?
update()– in-place modification (original set change होती है, None return होता है)।union()– new set return करता है, original unchanged रहती है।
Q4: Set methods किन iterables को accept करते हैं?
Q5: Frozenset में कौन से methods available हैं?
Frozenset में सिर्फ read-only methods हैं:copy(),union(),intersection(),difference(),symmetric_difference(),issubset(),issuperset(),isdisjoint(),count()(via__contains__)। Noadd,remove,update,pop,clear।
Summary Cheatsheet
📤 Output Blocks for Remaining Examples
Section 4: clear() Output
Before: {1, 2, 3, 4, 5}, len=5
After: set(), len=0
set()
set()
set()
{1, 2, 3}Section 5: copy() Output
True
False
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 999}Section 7: union() Output
{1, 2, 3, 4, 5}
{1, 2, 3}
{1, 2, 3, 4, 5, 6, 7}
{1, 2, 3, 4, 5, 6, 7, '8', '9'}
{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6, 7}Section 9: difference() Output
{1, 2}
{1, 2, 3, 4, 5}
{1, 2}
{1, 2}
{1, 2}
{6, 7}
{1, 2}
{1, 2}Section 10: symmetric_difference() Output
{1, 2, 5, 6}
{1, 2, 5, 6}
{1, 2, 5, 6}
{1, 2, 5, 6}
Added: {'date', 'elderberry'}
Removed: {'apple'}
Changed: {'apple', 'date', 'elderberry'}Section 11: issubset(), issuperset(), isdisjoint() Output
True False True True False True True False True True True False True False
Section 12: Operator vs Method Output
# A.union([4, 5]) → {1, 2, 3, 4, 5}
# A.union((4, 5)) → {1, 2, 3, 4, 5}
# A | [4, 5] → TypeError: unsupported operand type(s) for |: 'set' and 'list'⚠️ Common Mistakes
❌ Mistake 1: remove() पर KeyError handle नहीं करना
s = {1, 2, 3}
s.remove(99) # 💥 KeyError!KeyError: 99
✅ Fix: जब sure नहीं हो कि element है, तो discard() use करें या try-except लगाएं।
❌ Mistake 2: update() का return value use करना
None
✅ Fix: update() in-place modify करता है, return कुछ नहीं करता। New set चाहिए तो union() use करें।
❌ Mistake 3: Set में unhashable items add करना
TypeError: unhashable type: 'list' TypeError: unhashable type: 'dict'
✅ Fix: List को tuple में convert करें: s.add(tuple([4, 5]))
❌ Mistake 4: | operator के साथ list/tuple use करना
TypeError: unsupported operand type(s) for |: 'set' and 'list'
✅ Fix: Operator दोनों side sets चाहिए: A | set([4, 5]) या method use करें: A.union([4, 5])
❌ Mistake 5: Empty set {} से बनाना
s = {} # ❌ यह dict है, set नहीं!
print(type(s)) # <class 'dict'>
s = set() # ✅ Correct empty set
print(type(s)) # <class 'set'><class 'dict'> <class 'set'>
✅ Fix: Empty set बनाने के लिए हमेशा set() use करें, {} नहीं।
❌ Mistake 6: pop() से specific element expect करना
s = {10, 20, 30, 40, 50}
elem = s.pop() # कौन सा element आएगा? Unpredictable! 🎲✅ Fix: Specific element remove करना हो तो remove() या discard() use करें। pop() arbitrary element return करता है।
❌ Mistake 7: symmetric_difference() vs difference() confusion
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# difference: A में है, B में नहीं
print(A - B) # {1, 2}
# symmetric_difference: किसी एक में है, दोनों में नहीं
print(A ^ B) # {1, 2, 5, 6}{1, 2}
{1, 2, 5, 6}✅ Fix: difference = A-only elements। symmetric_difference = elements in exactly one set (either A-only OR B-only)।
✅ Key Takeaways
- 🔹
add()single element add करता है,update()multiple iterables से bulk add करता है। - 🔹
remove()missing element पर KeyError देता है,discard()silently ignore करता है — safe removal के लिएdiscard()prefer करें। - 🔹
pop()arbitrary element remove करता है — predictable removal चाहिए तोremove()/discard()use करें। - 🔹
union(),intersection(),difference()new set return करते हैं, original unchanged रहता है। - 🔹
update(),intersection_update(),difference_update()in-place modify करते हैं,Nonereturn करते हैं। - 🔹 Methods (
.union(),.intersection()) any iterable accept करते हैं, लेकिन operators (|,&) दोनों side sets require करते हैं। - 🔹
issubset(),issuperset(),isdisjoint()comparison methods हैं जो boolean return करते हैं — membership testing और validation में useful हैं। - 🔹
clear()in-place empty करता है (references affect होती हैं),s = set()new object बनाता है (old references unchanged)। - 🔹 Set में सिर्फ hashable (immutable) elements store होते हैं — list, dict, set नहीं add कर सकते।
- 🔹
symmetric_difference()exactly one set वाले elements देता है — change detection और toggle logic में बहुत useful है।
❓ FAQ
Q1: update() और add() में क्या difference है?
add()सिर्फ एक element add करता है।update()multiple iterables से सारे elements bulk में add करता है।s.add("hello")एक string element add करेगा, लेकिनs.update("hello")individual characters{'h', 'e', 'l', 'o'}add करेगा।
Q2: Set methods की time complexity क्या है?
add(),remove(),discard(),pop()→ O(1) average case।union(),intersection(),difference()→ O(len(A) + len(B))।issubset(),issuperset()→ O(len(smaller_set))। Hash table based implementation इन्हें fast बनाती है।
Q3: clear() और s = set() में क्या difference है?
clear()same object को in-place empty करता है — जो भी variables उस object को reference करते हैं, सब empty हो जाएंगे।s = set()एक new empty set बनाता है, पुराना object अगर कहीं और reference है तो unchanged रहता है।
Q4: symmetric_difference() real-world में कब use होता है?
जब दो states compare करने हों: file sync (कौन सी files changed), permissions audit (mismatched permissions), toggle operations, और "what's different" type queries में बहुत useful है।
Q5: क्या frozenset पर ये सभी methods काम करते हैं?
नहीं! Frozenset immutable है, इसलिएadd(),remove(),discard(),pop(),clear(),update(), और सभी_update()methods available नहीं हैं। सिर्फ read-only methods (union(),intersection(),issubset()etc.) काम करते हैं।
Q6: union() vs | operator — कौन सा better है?
दोनों same result देते हैं।union()method ज़्यादा flexible है क्योंकि any iterable accept करता है।|operator ज़्यादा readable है लेकिन दोनों sides पर sets require करता है। Performance difference negligible है।
Q7: pop() empty set पर call करें तो क्या होगा?
KeyError: 'pop from an empty set'raise होगा। इसलिए हमेशाif s:check करेंpop()से पहले, या try-except use करें।
Q8: Set methods chain कर सकते हैं क्या?
Read-only methods जो set return करते हैं (जैसेunion(),intersection()) chain हो सकते हैं:A.union(B).intersection(C)। लेकिन in-place methods (update(),add())Nonereturn करते हैं, इसलिए chain नहीं कर सकते।
🎯 Interview Questions (Detailed)
Q1: remove() और discard() में fundamental difference क्या है? कब कौन सा use करें?
Answer:remove(x)element missing होने परKeyErrorraise करता है — यह तब use करें जब element must exist हो और missing होना एक bug indicate करे।discard(x)silently ignore करता है — यह तब use करें जब element का होना optional हो। Production code मेंdiscard()safer है क्योंकि unexpected crashes avoid होती हैं।
Q2: Set operations की time complexity explain करें।
Answer: -add(),remove(),discard(),__contains__(in) → O(1) average (hash table lookup) -pop()→ O(1) (first available slot) -union(B)→ O(len(A) + len(B)) (iterate both, hash all) -intersection(B)→ O(min(len(A), len(B))) (iterate smaller, check in larger) -difference(B)→ O(len(A)) (iterate A, check not in B) -issubset(B)→ O(len(A)) (check each A element in B) - Worst case O(n) possible due to hash collisions, but rare with good hash functions।
Q3: update() और union() में key differences बताएं। Code example दें।
Answer:update()in-place modify करता है (returns None),union()new set return करता है (original unchanged)। ``python A = {1, 2, 3} B = {4, 5} result = A.union(B) # A unchanged, result = {1,2,3,4,5} A.update(B) # A modified to {1,2,3,4,5}, returns None`Memory efficiency:update()better है जब original set modify करना ठीक हो,union()` जब immutability preserve करनी हो।
Q4: Set operators (|, &, -, ^) और methods (union, intersection, difference, symmetric_difference) में practical difference क्या है?
Answer: Operators दोनों operands set type require करते हैं। Methods any iterable accept करते हैं (list, tuple, range, generator)। इसलिए methods ज़्यादा flexible हैं: ``python s = {1, 2, 3} s.union([4, 5]) # ✅ Works s | [4, 5] # ❌ TypeError `` Performance same है, readability operators में better होती है जब दोनों sets हों।Q5: issubset(), issuperset(), isdisjoint() के practical use cases बताएं।
Answer: -issubset(): Permission checking — user permissions ⊆ required permissions -issuperset(): Feature completeness — available features ⊇ needed features -isdisjoint(): Conflict detection — two schedules don't overlap ``python user_roles = {"read", "write"} required = {"read"} print(required.issubset(user_roles)) # True → access granted``
Q6: symmetric_difference() real-world scenario में कैसे use करें?
Answer: State comparison और change detection में useful है: ``python yesterday_users = {"alice", "bob", "charlie"} today_users = {"bob", "charlie", "dave", "eve"} changes = yesterday_users ^ today_users # {'alice', 'dave', 'eve'} → ये users changed (left or joined) new_users = today_users - yesterday_users # {'dave', 'eve'} left_users = yesterday_users - today_users # {'alice'} `` File sync, database migrations, और config drift detection में widely used है।Q7: clear() vs reassignment (s = set()) — memory और reference behavior explain करें।
Answer: ``python a = {1, 2, 3} b = a # same object reference a.clear() # in-place → b भी empty! # vs a = {1, 2, 3} b = a a = set() # new object → b unchanged {1, 2, 3}`clear()same memory location modify करता है — सभी references affect होती हैं। Reassignment new object create करता है — old references unchanged। Garbage collection perspective सेclear()` same object reuse करता है।
Q8: Set comprehension में methods कैसे efficiently combine करें?
Answer: ``python # Find common skills across multiple teams teams = [ {"python", "java", "sql"}, {"python", "javascript", "sql"}, {"python", "go", "sql", "rust"} ] common = set.intersection(*[set(t) for t in teams]) # {'python', 'sql'} # Unique skills across all teams all_skills = set.union(*teams) # {'python', 'java', 'sql', 'javascript', 'go', 'rust'}`set.intersection(*iterables)औरset.union(*iterables)` class method style से multiple sets efficiently combine होते हैं।
Q9: Frozenset पर कौन से methods available हैं और क्यों?
Answer: Frozenset immutable है, इसलिए सिर्फ non-mutating methods available हैं: - ✅ Available:copy(),union(),intersection(),difference(),symmetric_difference(),issubset(),issuperset(),isdisjoint()- ❌ Not available:add(),remove(),discard(),pop(),clear(),update(), सभी_update()methods Frozenset hashable है, इसलिए set-of-sets या dict key बन सकता है: ``python fs = frozenset([1, 2, 3]) d = {fs: "value"} # ✅ dict key as frozenset``
Q10: Production code में set methods का best practice pattern क्या है?
Answer: ``python # 1. Safe removal s.discard(x) # prefer over remove() unless KeyError needed # 2. Check before pop elem = s.pop() if s else None # 3. Immutable operations for functional style result = a.union(b).difference(c) # chain without side effects # 4. Use operators for readability when both are sets common = set_a & set_b # cleaner than intersection() # 5. Bulk operations with update variants s.update(list1, list2, list3) # one call instead of loop`Key principle: Choose between in-place और new-set based on whether original data preserve करना है या नहीं। Defensive coding मेंdiscard()>remove()` prefer करें।
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Set Methods – Complete Reference.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, data, structures, set
Related Python Master Course Topics