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 sur les fichiers Python

Objets et classes Python

Dates et heures Python

Connaissances avancées Python

Manuel de référence Python

Méthode d'utilisation et exemple de remove() dans la collection Python

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)

remove() parameter

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.

remove() return value

The remove() method only deletes the given element from the set. It does not return any value.

Example1: Delete elements from the set

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

Example2: Try to delete an element that does not exist

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

Méthodes de collection en Python