Remove items from Set Python (original) (raw)
Last Updated : 19 Apr, 2025
We are given a set and our task is to remove specific items from the given set. **For example, if we have **a = {1, 2, 3, 4, 5} and need to remove 3, the resultant set should be ****{1, 2, 4, 5}**.
Using remove()
**remove() method in Python is used to remove a specific item from a set. If the item is not present it raises a **KeyError so it's important to ensure item exists before using it.
Python `
a = {1, 2, 3, 4, 5}
a.remove(3)
print(a)
`
**Explanation:
- **a.remove(3) removes element "3" from the set a and if element is not found then it raises a **KeyError.
- after removal of element, set a is printed and element "3" is no longer part of the set.
Using discard()
**discard() method in Python removes a specified element from a set without raising a KeyError even if element does not exist in set. It's a safer alternative to **remove() as it doesn't cause an error when element is missing.
Python `
a = {1, 2, 3, 4, 5}
a.discard(3) a.discard(6)
print(a)
`
**Explanation:
- **discard(3) method removes element "3" from the set a if it exists.
- **discard(6) method does nothing because "6" is not present in set and no error is raised.
Using pop()
**pop() method removes and returns a random element from a set. Since sets are unordered element removed is arbitrary and may not be predictable.
Python `
a = {1, 2, 3, 4, 5} r = a.pop() print(f"Removed: {r}") print(a)
`
Output
Removed: 1 {2, 3, 4, 5}
**Explanation:
- **pop() method removes and returns a random element from the set ****"a"** and removed element is stored in variable ****"r"**.
- After removal, set ****"a"** is printed showing remaining elements without randomly chosen item.
Using clear()
**clear() method removes all elements from a set effectively making it an empty set. It does not return any value and directly modifies original set.
Python `
a = {1, 2, 3, 4, 5}
a.clear()
print(a)
`