Account
Categories

Python Set add() Method


Definition

If you use the add() method in your program, it adds only one element and ignores values that are already in the set.

Now you will clearly understand the method through the flowchart.

s = {10, 20}

========================
CASE 1: New Value
========================

add(30)

   30
      │
      ▼
{10, 20}
      │
      ▼
{10, 20, 30}

========================
CASE 2: Duplicate Value
========================

add(20)

   20
      │
      ▼
{10, 20}
      │
      ▼
NO CHANGE

{10, 20}

Syntax:

set_name.add(element)

Example 1:

s = {10, 20}
s.add(30)
print(s)

Output:

Example 2:

s = {10, 20}
s.add(20)
print(s)

Output:

Exercise

Create a set s = {1, 2} and add 3 into it.