Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
remove vs discardAlthough sets do not maintain sequence indices, they are fully mutable collections. You can register new unique entries on the fly, ingest bulk data from other iterables, and purge values when they are no longer needed.
When removing items from a set, Python presents one of its most important design distinctions: the difference between remove() (which strictly raises a KeyError if the element does not exist) and discard() (which silently ignores missing elements).
+-------------------------------------------------------------------------+
| ADDING & REMOVING SET ITEMS REAL-WORLD ANALOGY |
+-------------------------------------------------------------------------+
1. ADD (Adding a Single Member):
- An admin in a residential society WhatsApp group adds a new resident:
group.add("Flat-402")
- If Flat-402 is already in the group, WhatsApp doesn't create a clone;
it simply ignores the duplicate!
2. UPDATE (Bulk Import from Multiple Blocks):
- The society secretary imports all residents from Block B and Block C:
group.update(["Flat-501", "Flat-502"], ("Flat-601", "Flat-602"))
- Unpacks all iterables simultaneously and absorbs their unique tokens.
3. REMOVE vs DISCARD (The Security Gate Guard):
- remove("Visitor_Pass_99"): The guard strictly demands pass 99.
If the visitor doesn't have it, an alarm blares: KeyError!
- discard("Visitor_Pass_99"): The guard says: "If pass 99 is on the
board, toss it into the bin; if not, no problem, keep moving!"
+-------------------------------------------------------------------------+remove() vs discard() Decision Treeadd() and update()To insert data into a set:
set.add(item): Inserts a single hashable element.set.update(iterable1, iterable2, ...): Unpacks any number of iterables (lists, tuples, sets, strings) and inserts all distinct elements.remove() vs discard()Always choose intentionally between strict deletion (remove) and fault-tolerant deletion (discard):
pop(), clear(), and delAdditional deletion operations:
| Scenario | ❌ Anti-Pattern | ✅ Pythonic Idiom |
|---|---|---|
| Safe Deletion | Calling s.remove(x) without guarding | Use s.discard(x) if missing item is acceptable |
| Add Multiple Items | Running a loop calling s.add() repeatedly | s.update([item1, item2, item3]) |
| Add String as Single Word | Calling s.update("DELHI") (Splits into chars!) | s.add("DELHI") or s.update(["DELHI"]) |
| Emptying a Set | s = set() (Rebinds reference) | s.clear() (Clears in-place) |
| Pop from Empty Set | Calling empty_set.pop() (KeyError) | Check if my_set: before calling pop() |
+---------------------------------------------------------------------------+ | SET MUTATION METHODS CHEAT SHEET | +---------------------------------------------------------------------------+ | Method / Statement | Action / Behavior | |-----------------------+---------------------------------------------------| | set.add(x) | Adds single hashable item x | | set.update(iterables)| Ingests elements from one or more iterables | | set.remove(x) | Deletes x; raises KeyError if x is missing | | set.discard(x) | Deletes x; silently does nothing if x is missing | | set.pop() | Removes & returns arbitrary item (KeyError if set)| | set.clear() | Empties the set in-place | | del set_var | Deletes the variable from memory scope | +---------------------------------------------------------------------------+
{}Curly braces {} create an empty dictionary, not an empty set!
Sets are unordered collections with no fixed position. They cannot be indexed:
set.remove(x) and set.discard(x)?A. remove() takes only strings, while discard() takes numbers B. If x is absent, remove() raises a KeyError, whereas discard() silently does nothing C. remove() deletes all occurrences, while discard() deletes only one D. discard() returns a boolean, while remove() returns the item
s = {"A", "B"}; s.update("CD")?A. Adds the single string "CD" to s B. Unpacks the string into characters and adds 'C' and 'D' individually to s C. Raises a TypeError D. Creates a nested set inside s
set.pop() do when called on a populated set?A. Removes and returns the last element added B. Removes and returns the first element by alphabetical order C. Removes and returns an arbitrary element because sets are unordered D. Clears the entire set
fruits after:A. 4 B. 3 C. 2 D. 1
pop() is executed on an empty set s = set()?A. IndexError B. ValueError C. KeyError: 'pop from an empty set' D. None is returned
Build an emergency triage register for a hospital in New Delhi. Manage active urgent patient cases using a set: add incoming patient IDs (add), ingest batch transfers from ambulance units (update), discharge treated patients safely without crashing (discard), handle priority room allocation via arbitrary dispatch (pop), and clear the ward at change of shift.
In the next lesson, we will continue your Python learning journey with Set Operations (10: Sets).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Sets Introduction | Set Operations |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.