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

Tutoriel de base Python

Contrôle de flux Python

Fonctions en Python

Types de données en Python

Opérations de fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Utilisation et exemple de remove() de la liste Python

Python list methods

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)

paramètres de remove()

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

retourne la valeur

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

Example1: Delete elements from the 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: Usage of 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 elements

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

Python list methods