English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutorial Básico Python

Controle de Fluxo Python

Funções do Python

Tipos de Dados do Python

Operações de Arquivos Python

Objetos e Classes Python

Data e Hora Python

Conhecimento Avançado Python

Manual de Referência Python

Uso e exemplo do remove() da lista Python

Python list methods

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)

parâmetros do remove()

  • 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.

retorna valor

remove() does not return any value (returns None).

Example1: Delete element from list

# 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']

Example2: Using remove() on a list with duplicate elements

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.

Example3: Delete non-existent element

# 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.

Python list methods