Set add() Method in Python

Python Set add() Method

The add() method is used to add a single element to a set. Sets are unordered collections of unique elements, and the add() method ensures that the element being added is not a duplicate.

Syntax of the add() method:

your_set.add(element)

Parameters:

  • your_set: This is the set to which you want to add an element.
  • element: The element you want to add to the set.

Example:

# Creating an empty set
fruits = set()

# Adding elements to the set using add()
fruits.add('apple')
fruits.add('banana')
fruits.add('orange')

print(fruits)  # Output: {'apple', 'banana', 'orange'}

# Trying to add a duplicate element
fruits.add('apple')
print(fruits)  # Output: {'apple', 'banana', 'orange'} (still the same, 'apple' was not added again)

As you can see, when we tried to add the 'apple' element again, it didn't get added since sets only allow unique elements. If the element already exists in the set, the add() method will simply ignore the operation.