English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode remove() supprime le premier élément correspondant de la liste (transmis en tant que paramètre).
la syntaxe de la méthode remove() est :
list.remove(element)
La méthode remove() prend un élément en tant que paramètre et le supprime de la liste.
si l'élément n'existe pas, une exception sera lancéeValueError : list.remove(x) : x n'est pas dans la liste exception.
remove() does not return any value (returns None).
# Animal list animals = ['cat', 'dog', 'rabbit', 'tiger'] # 'tiger' is removed animals.remove('tiger') # Updated animal list print('Updated animal list: ', animals)
Output results
Updated animal list: ['cat', 'dog', 'rabbit']
If the list contains duplicate elements, the remove() method only deletes the first matching element.
# Animal list animals = ['cat', 'dog', 'dog', 'rabbit', 'tiger', 'dog'] # 'dog' is removed animals.remove('dog') # Updated list print('Updated list: ', animals)
Output results
Updated list: ['cat', 'dog', 'rabbit', 'tiger', 'dog']
Here, only the first occurrence of the animal 'dog' is removed from the list.
# Animal list animals = ['cat', 'dog', 'rabbit', 'guinea pig'] # Delete 'fish' element animals.remove('fish') # Updated list print('Updated list: ', animals)
Output results
Traceback (most recent call last): File ".. .. ..", line 5, in <module> animal.remove('fish') ValueError: list.remove(x): x not in list
Here, since the 'fish' is not contained in the 'animals' list, the program throws an error after running.
If you need to delete elements based on index (for example, the fourth element), you can usepop() method.
In addition, you can usePython del statementRemove items from the list.