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ção de arquivo Python

Python object and class

Python date and time

Python advanced knowledge

Python reference manual

Python set add() usage and example

Métodos do Conjunto do Python

The set add() method adds the given element to the set. If the element already exists, it does not add any elements.

set The syntax of the add() method is:

set.add(elem)

If the element already exists, the add() method will not add it to the set.

In addition, if the add() method is used when creating the set object, it will not return the set.

noneValue = set().add(elem)

The above statement does not return a reference to the set, but returns 'None', because the return type of the add is 'None',

add() parameter

The add() method takes one parameter:

  • elem -The element added to the set

add() return value

The add() method does not return any value and returns“ None”.

Example1: Add element to set

# Vowel set
vowels = {'a', 'e', 'i', 'u'}
# Add 'o'
vowels.add('o')
print('The vowel set is:', vowels)
# Add 'a' again
vowels.add('a')
print('The vowel set is:', vowels)

When running the program, the output is:

The vowel set is: {'a', 'i', 'o', 'u', 'e'}
The vowel set is: {'a', 'i', 'o', 'u', 'e'}

Note:The order of vowels can be different.

Example2: Add tuple to set

# Set of vowels
vowels = {'a', 'e', 'u'}
# Tuple 'i', 'o'
tup = ('i', 'o')
# Add tuple
vowels.add(tup)
print('The vowel set is:', vowels)
# Add the same tuple again
vowels.add(tup)
print('The vowel set is:', vowels)

When running the program, the output is:

The vowel set is: {('i', 'o'), 'e', 'u', 'a'}
The vowel set is: {('i', 'o'), 'e', 'u', 'a'}

You can also addTupleAdd to the set. Like ordinary elements, you can only add the same tuple once.

Métodos do Conjunto do Python