In Python, you can remove items from a set using several methods. Here’s how each one works:
Removing a Specific Item with remove()
The remove() method deletes a specific item from the set. If the item doesn’t exist, it raises a keyError.
data_set = {1, 2, 3, 4, 5}
data_set.remove(4)
print(data_set) # Output: {1, 2, 3, 5}
# Trying to remove an item that doesn't exist
# data_set.remove(6) # Raises KeyError
Removing a Specific Item with discard()
The discard() method also deletes a specific item from the set, but if the item doesn’t exist, it doesn’t raise an error.
data_set = {1, 2, 3, 4, 5}
data_set.discard(4)
print(data_set) # Output: {1, 2, 3, 5}
data_set.discard(6) # No error if 6 isn't in the set
Removing and Returning a Random Item with pop()
The pop() method removes and returns a random item from the set. Since sets are unordered, you won’t know which item will be removed.
data_set = {10, 20, 30, 40, 50}
removed_item = data_set.pop()
print("Removed item:", removed_item) //50
print("Set after pop:", data_set) // {10, 20, 30, 40}
# Output will vary because pop removes a random item
Removing All Items with clear()
The clear() method removes all items from the set, leaving it empty.
data_set = {1, 2, 3, 4, 5}
data_set.clear()
print(data_set) # Output: set()
Python Remove Items from Sets – Interview Questions
Q 1: How do you remove an item from a set?
Q 2: What is the difference between remove() and discard()?
Q 3: How do you remove an arbitrary element?
Q 4: How do you clear all items from a set?
Q 5: Can set removal affect other sets?
Python Remove Items from Sets – Objective Questions (MCQs)
Q1. Which method removes a specified element from a set and raises an error if it doesn't exist?
Q2. Which method removes a specified element without raising an error if it doesn't exist?
Q3. What will be the output of the following code?
s = {1, 2, 3}
s.pop()
print(s)
Q4. What does the clear() method do in sets?
Q5. What is the correct way to delete the entire set variable?