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:

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:

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:

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)

`