Python Set add() Method

Python3 列表Python Sets


Description

The add() method is used to add an element to a set. If the element being added already exists in the set, no operation is performed.

Syntax

Syntax of the add() method:

set.add(elmnt)

Parameters

  • elmnt -- Required, the element to be added.

Return Value

None.

Examples

The following examples demonstrate the use of the add() method:

Example 1

fruits = {"apple", "banana", "cherry"} fruits.add("orange") print(fruits)

The output result is:

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

If the element already exists, no add operation is performed:

Example 2

fruits = {"apple", "banana", "cherry"} fruits.add("apple") print(fruits)

The output result is:

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

Python3 列表Python Sets

Other Extensions