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 update() de la collection Python

Méthodes de l'ensemble en Python

The Python set update() method updates the set and adds items from other iterable objects.

The syntax of update() is:

A.update(iterable)

Here, A is a set, and iterable can be any iterable object, such as a list, set, dictionary, string, etc. Add the elements of the iterable to the set A.

Let's take another example:

A.update(iter1, iter2, iter3)

Here, the elements of iterables are iter1, iter2and iter3is added to the set A.

update() return value

The update() method returns None (returns nothing).

Example1: Python set update()

A = {'a', 'b'}
B = {1, 2, 3}
result = A.update(B)
print('A =', A)
print('result =', result)

Output result

A = {'a', 1, 2, 3, 'b'}
result = None

Example2: Add string and dictionary elements to Set

string_alphabet = 'abc'
numbers_set = {1, 2}
# Add the elements of the string to the set
numbers_set.update(string_alphabet)
print('numbers_set =', numbers_set)
info_dictionary = {'key': 1, 'lock' : 2}
numbers_set = {'a', 'b'}
# Add the keys of the dictionary to the set
numbers_set.update(info_dictionary)
print('numbers_set =', numbers_set)

Output result

numbers_set = {'c', 1, 2, 'b', 'a'}
numbers_set = {'key', 'b', 'lock', 'a'}

Note:If a dictionary is passed to the update() method, the keys of the dictionary are added to the set.

Méthodes de l'ensemble en Python