.update()

Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jul 2, 2024
Contribute to Docs

In Python, the .update() method updates the current set by adding items from another iterable, such as a set, list, tuple, or dictionary. It also removes any duplicates, ensuring that all the elements in the original set occur only once.

Syntax

set.update(iterable)

Or, the alternative syntax is:

set |= iterable
  • set: The set to which elements are to be added.
  • iterable: The collection of elements to be added to set.

Note: The .update() method in Python allows updating a set directly with multiple iterable objects passed as arguments.

Example

In the example below, two sets, set1 and set2, are created. The .update() method is then called on set1, with set2 as the argument:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Using the '.update()' method to update 'set1' with 'set2'
set1.update(set2)
print(set1)
# Using the alternative syntax to update 'set1' with 'set2'
set1 |= set2
print(set1)

The output would be the following:

{1, 2, 3, 4, 5}
{1, 2, 3, 4, 5}

Codebyte Example

In this example, when updating a set set1 with a dictionary dict1, only the keys of the dictionary are added to the set:

us
Visit us
code
Hide code
Code
Output
Hide output
Hide output
Loading...

All contributors

Looking to contribute?

Learn Python on Codecademy