set.add()
set.add(elem) None · Updated March 15, 2026 · Set Methods The .add() method inserts an element into a set. Since sets only store unique elements, adding a duplicate has no effect — the set remains unchanged. This operation is O(1) on average, making it efficient for building collections of unique items.
Syntax
set.add(elem)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
elem | any | — | The element to add to the set. Must be hashable (immutable type). |
Examples
Basic usage
Add a single element to an existing set:
fruits = {"apple", "banana"}
fruits.add("cherry")
print(fruits)
# {'apple', 'banana', 'cherry'}
Adding duplicate values
Sets ignore duplicates — adding an element that already exists does nothing:
numbers = {1, 2, 3}
numbers.add(2)
print(numbers)
# {1, 2, 3} # No change, 2 was already present
This behavior is useful when you don’t know whether an item exists in the collection beforehand.
Adding different types
Sets can contain mixed hashable types:
mixed = set()
mixed.add(42)
mixed.add("hello")
mixed.add(3.14)
mixed.add((1, 2, 3)) # Tuples are hashable
print(mixed)
# {42, 'hello', 3.14, (1, 2, 3)}
Unhashable types will fail
Lists and dictionaries are mutable and cannot be added to sets:
my_set = {1, 2}
try:
my_set.add([3, 4]) # Raises TypeError
except TypeError:
print("Cannot add list to set")
# Cannot add list to set
# Use a tuple instead
my_set.add((3, 4))
The error occurs because Python needs elements to be hashable (immutable) to store them in a set.
Working with custom objects
You can add instances of custom classes to sets if they are hashable:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __hash__(self):
return hash((self.x, self.y))
def __eq__(self, other):
return self.x == other.x and self.y == other.y
points = set()
p1 = Point(1, 2)
points.add(p1)
points.add(Point(1, 2)) # Duplicate, won't be added
print(len(points)) # 1
Common Patterns
Building a unique collection
A common pattern is building a set from input data to remove duplicates:
user_inputs = ["apple", "banana", "apple", "cherry", "banana"]
unique_fruits = set()
for fruit in user_inputs:
unique_fruits.add(fruit)
print(unique_fruits)
# {'apple', 'banana', 'cherry'}
While this works, using the set constructor is more concise for this specific task.
Tracking seen items
Sets are ideal for tracking processed items to avoid duplicates:
processed = set()
incoming = [101, 102, 101, 103, 102, 104]
for item in incoming:
if item in processed:
print(f"Duplicate: {item}")
else:
processed.add(item)
print(f"New item: {item}")
This pattern is common in data pipelines, web scraping, and anywhere you need to filter unique items.
Character uniqueness checking
Verify that all characters in a string are unique:
def has_unique_chars(s):
chars = set()
for char in s:
if char in chars:
return False
chars.add(char)
return True
print(has_unique_chars("abcde")) # True
print(has_unique_chars("hello")) # False (l is repeated)
This can be simplified using the fact that adding a duplicate to a set doesn’t raise an error:
def has_unique_chars(s):
return len(set(s)) == len(s)
Performance
The .add() method has:
- Average case: O(1) time complexity
- Worst case: O(n) when the hash table needs resizing
The constant-time average performance makes sets ideal for membership testing and deduplication tasks.
See Also
- set::set — the set constructor
- list::list.append — similar method for lists