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

Tutorial básico Python

Controle de fluxo Python

Função do Python

Tipos de Dados do Python

Operações de arquivos Python

Objetos e classes Python

Data e hora Python

Conhecimentos avançados Python

Manual de referência Python

Métodos e exemplos de uso da função remove() de conjuntos Python

Métodos de Conjunto do Python

The remove() method searches for the given element in the set and removes 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.

elementdoes not exist,the parameterthenraiseskeyErrorException.

remove() return value

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

Example1: Remove element from 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 a non-existent element

# 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étodos de Conjunto do Python