Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Set add() method



The Python Setadd() method is used to add a single element to a set. If the element is already present in the set the set remains unchanged because sets do not allow duplicate elements. The add() method modifies the set in place and does not return any value. The adding of the element will be happen if the element is unique in the set.

Syntax

Following is the syntax and parameters of Python Setadd() method −

set.add(element)

Parameter

This method accepts the following parameter −

element: The element to be added to the set. This can be any hashable type such as numbers, strings or tuples.

Return value

This method does not return a value.

Example 1

Following is the basic example of the Python Setadd() method. Here we are creating a set with 3 elements and adding a fourth element to it.

# Define a setmy_set = {1, 2, 3}# Add an element to the setmy_set.add(4)# Print the updated setprint(my_set)

Output

{1, 2, 3, 4}

Example 2

Since sets in Python doesn't allow duplicate elements if we try to add an existing element using this method the contents of the set remain unchanged. In the example below we are trying to add an existing element (3) to the set.

# Define a setmy_set = {1, 2, 3}# Add a duplicate element to the setmy_set.add(3)# Print the updated setprint(my_set)

Output

{1, 2, 3}

Example 3

We also add different types of data to a set. In here, we are creating an empty set and adding an integer, string and a tuple to it, using the add() method −

# Define an empty setmy_set = set()# Add elements of different types to the setmy_set.add(1)my_set.add("Hello")my_set.add((1, 2, 3))# Print the updated setprint(my_set)

Output

{1, (1, 2, 3), 'Hello'}

Example 4

Now, lets try to add multiple elements to a set using a loop.

# Define an empty setmy_set = set()# Add elements to the set in a loopfor i in range(5):    my_set.add(i)# Print the updated setprint(my_set)

Output

{0, 1, 2, 3, 4}
python_set_methods.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp