English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Méthodes de collection en Python
The remove() method searches for the given element in the set and deletes it.
The syntax of the remove() method is:
set.remove(element)
The remove() method takes a single element as a parameter and removes it fromsetremove.
If the element passed to the remove() methodelementthe parameter does not exist,thentriggerkeyErrorException.
The remove() method only deletes the given element from the set. It does not return any value.
# language set language = {'English', 'French', 'German'} # Delete 'German' language.remove('German') # Update language set print('Updated language set: ', language)
The output when running the program is:
Updated language set: {'English', 'French'}
# animal set animal = {'cat', 'dog', 'rabbit', 'pig'} # Delete 'fish' element animal.remove('fish') # Update animal set print('Update animal set: ', animal)
The following error will occur when running the program:
Traceback (most recent call last): File '<stdin>', line 5, in <module> animal.remove('fish') KeyError: 'fish'
This is because the element 'fish' does not exist in the animal set.
If you do not want to see this error, you can usediscard() method. If the element passed to the discard() method does not exist, the set remains unchanged.
A set is an unordered collection of elements. If you need to delete any element from the set, you can usepop() method.