Python Set add() Method

The Python add() method adds a single element to the set.

Syntax

set.add(element)

Parameters

element: The item to add to the set (must be hashable).

Return Value

Returns None (modifies the set in-place).

Example 1: Add an Element to a Set

fruits = {"apple", "banana"}
fruits.add("mango")
print(fruits) # Output: {'apple', 'mango', 'banana'}

Python sets are unordered, so items may appear in a different order each time you print them.

Example 2: Adding a Duplicate

If the element already exists in the set, nothing happens because sets do not allow duplicates.

For exampe:

fruits = {"apple", "banana"}
fruits.add("banana")
print(fruits) # Output: {'apple', 'banana'}

Example 3: Adding Unhashable Types

You can only add hashable objects (such as numbers, strings, or tuples) to a set. Mutable types like lists or dictionary cannot be added.

For example:

fruits = {"apple", "banana"}
fruits.add(["mango", "orange"]) # Raises TypeError
print(fruits)