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

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Set add() Usage and Example

Méthodes de l'ensemble en Python

The set add() method adds the given element to the set. If the element already exists, no element is added.

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

# Vowel set as set
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éthodes de l'ensemble en Python