Python Set remove() Method
Removes an item from the set. If the item does not exist in the set,
Python will throw a KeyError
exception. Compare this to the
discard
method which will not throw
an exception if the item doesn't exist.
Syntax
Python
Copy Code
set.remove(item)
Parameters
Parameter | Description |
---|---|
item |
Required. The item to remove from the set. |
Example
Python
Copy Code
laptopComponents = {'memory', 'processor', 'SSD', 'camera', 'keyboard'} laptopComponents.remove('SSD') print(laptopComponents) print("Removing an item that doesn't exist in the set:") laptopComponents.remove('display')
Output
{'keyboard', 'processor', 'memory', 'camera'} Removing an item that doesn't exist in the set: Traceback (most recent call last): File "Sets.py", line 5, in <module> laptopComponents.remove('display') KeyError: 'display'