set.add() / set.remove() / set.discard()
Methods for adding and removing elements from a set. A set is a collection of unique elements that allows you to quickly check whether an element exists.
Syntax
# Adds an element to the set. set.add(element) # Removes an element (raises an error if it does not exist). set.remove(element) # Removes an element (does nothing if it does not exist). set.discard(element) # Removes and returns an arbitrary element. set.pop() # Removes all elements. set.clear()
Method List
| Method | Description |
|---|---|
| set.add(element) | Adds an element to the set. If the element already exists, nothing happens. |
| set.remove(element) | Removes the specified element from the set. Raises a KeyError if the element does not exist. |
| set.discard(element) | Removes the specified element from the set. Does nothing if the element does not exist — no error is raised. |
| set.pop() | Removes and returns an arbitrary element from the set. Raises a KeyError if the set is empty. |
| set.clear() | Removes all elements from the set, leaving it empty. |
| set.update(iterable) | Adds all elements from an iterable (such as a list or another set) to the set. |
Sample Code
# Create a set and add an element.
fruits = {'apple', 'banana'}
fruits.add('cherry')
print(fruits) # Prints something like {'apple', 'banana', 'cherry'} (order is not guaranteed).
# Adding a duplicate element has no effect.
fruits.add('apple')
print(len(fruits)) # Prints '3'.
# Remove an element with remove().
fruits.remove('banana')
print(fruits) # Prints something like {'apple', 'cherry'}.
# Removing a non-existent element with remove() raises an error.
try:
fruits.remove('grape') # Raises KeyError.
except KeyError as e:
print(f'Error: {e}')
# discard() does not raise an error if the element does not exist.
fruits.discard('grape') # No error.
print(fruits) # The set is unchanged.
# Add all elements from a list with update().
new_items = ['mango', 'apple', 'kiwi']
fruits.update(new_items)
print(fruits) # Elements are added without duplicates.
# Remove an arbitrary element with pop().
removed = fruits.pop()
print(f'Removed element: {removed}')
# Remove all elements with clear().
fruits.clear()
print(fruits) # Prints 'set()' (an empty set).
Notes
Unlike lists, sets are unordered and cannot contain duplicate elements. This makes adding, removing, and checking for elements faster than with a list. There are two methods for removing elements: remove() and discard(). Use remove() when you want an error to be raised if the element does not exist, and discard() when you want to silently ignore missing elements.
Because sets are unordered, pop() does not guarantee which element is removed. If you need to retrieve a specific element, use a list or a deque (collections.deque) instead.
For set operations such as union, intersection, and difference, see 'set.union() / set.intersection() / set.difference()'.
If you find any errors or copyright issues, please contact us.