Python Set add() Method – Tutorial with Examples

Python Set add() Method

The add() method in Python Set is used to add a single element to a set. It modifies the original set and returns None.

Basic Syntax

set.add(element)

Here, set is the set in which the element has to be added and element is the element which is to be added to the set.

Parameters

  • element: It is the element to be added to the set.

Return Value

The add() method does not return anything. It updates the set with the given element.

Examples

Example 1: Add an element to a set

In this example, we will add an element to the set using the add() method.

# Creating a set
fruits = {"apple", "banana", "cherry"}
# Adding an element to the set
fruits.add("orange")

# Printing the updated set
print(fruits)

The output of the above code will be:

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

As we can see, the add() method has added the element “orange” to the set “fruits”.

Example 2: Add multiple elements to a set using for loop

In this example, we will use a for loop to add multiple elements to a set using the add() method.

# Creating an empty set
numbers = set()
# Adding elements to the set using a for loop
for i in range(1, 6):
    numbers.add(i)

# Printing the updated set
print(numbers)

The output of the above code will be:

{1, 2, 3, 4, 5}

The above code adds the integers from 1 to 5 to the set “numbers” using the add() method inside a for loop.

Example 3: Add a tuple to a set

In this example, we will add a tuple to a set using the add() method.

# Creating a set
fruits = {"apple", "banana", "cherry"}
# Adding a tuple to the set
fruits.add(("mango", "papaya"))

# Printing the updated set
print(fruits)

The output of the above code will be:

{'banana', 'apple', 'cherry', ('mango', 'papaya')}

The above code adds a tuple (“mango”, “papaya”) to the set “fruits” using the add() method.

Use Cases

  • The add() method is used to add elements to a set without creating a new set. This makes it more efficient than creating a new set and then adding elements to it.
  • The add() method can be used to add elements to a set in a loop or conditionally, making it useful in situations where new elements may be added to a set over time.
  • The add() method is also useful in situations where we want to add a single element to a set without worrying about duplicates. If the element already exists in the set, the add() method will not add it again.

Leave a Reply

Your email address will not be published. Required fields are marked *