Account
Categories

Python Set update() Method


Definition

If you use the update() method in your program, it adds more elements; if these elements are already present in the set, it does not add them and discards them.

Now you will clearly understand the method through the flowchart.

s = {11, 12}

========================
CASE 1: New Values
========================

update([13, 14])

   13, 14
          │
          ▼
{11, 12}
          │
          ▼
{11, 12, 13, 14}

========================
CASE 2: Duplicate Values
========================

s = {11, 12, 13, 14}

update([13, 14])

   13, 14
          │
          ▼
{11, 12, 13, 14}
          │
          ▼
NO CHANGE

{11, 12, 13, 14}

Syntax:

set_name.update(iterable)

Example 1:

s = {11, 12}
s.update([13, 14])
print(s)

Output:

Example 2:

s = {11, 12, 13, 14}
s.update([13, 14])
print(s)

Output:

Exercise

Create a set s = {1, 2, 3} and remove 2 from it.