English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O método remove() remove o primeiro elemento que coincide (passado como parâmetro) da lista.
a sintaxe do método remove() é:
list.remove(element)
O método remove() aceita um elemento como parâmetro e o remove da lista.
Se o elemento não existir, será lançadaValueError: list.remove(x): x não está na lista exceção.
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 included in the animals list, the program throws an error after running.
If you need to delete an element based on index (for example, the fourth element), you can usepop() method.
In addition, you can usePython del statementRemove items from the list.