Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Set add() Method

Python Set add() Method

Python3 Lists Python Sets


Description

The add() method adds an element to a set; if the element already exists in the set, nothing is done.

Syntax

Syntax of the add() method:


set.add(elmnt)

Parameters

Return Value

none.

Example

The following example demonstrates the use of the add() method:

Example 1

fruits

= {

"

apple

"

,

"

banana

"

,

"

cherry

"

}

fruits

.

add

(

"

orange

"

)

print

(

fruits

)

The output is:


{'apple', 'banana', 'orange', 'cherry'}

For an element that already exists, no addition is performed:

Example 2

fruits

= {

"

apple

"

,

"

banana

"

,

"

cherry

"

}

fruits

.

add

(

"

apple

"

)

print

(

fruits

)

The output is:


{'apple', 'banana', 'cherry'}

Python3 Lists Python Sets