Python Set add()

Python’s set.add(element) method adds the element to this set. If the element is already present in the set, the method returns without any side effect.

Here’s a minimal example where we add element 4 to an existing set:

>>> s = {1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}

Syntax

Let’s dive into the formal syntax of the set.add() method.

set.add(element)
ArgumentData TypeExplanation
elementhashable objectAn hashable object to be added to the set.

Return Value of Set add()

The return value of set.add() is None.

What is a Hashable Object?

You can only add hashable objects to a set. But what does it mean for an object to be hashable?

Hashing an object means that you put it through a hash function that assigns an integer to the object. Python does this by means of the object.__hash__() “dunder” or “double-underscore” method. This method defines the behavior for an object if you pass it into Python’s built-in hash() function.

Python’s built-in hash(object) function takes one object as an argument and returns its hash value. As the hash value is calculated based on the object’s data, two different but equal objects must have the same hash value.

You can learn everything about it in this video:

Why is it important for an object to be hashable?

The reason is simple: the set and dictionary data structures are based on a so-called hash table data structure. This data structure allows for quick retrieval of any given object just by calling its hash function. Think of it this way: the return value of the hash function hints on the location of the element in the container data structure.

This is the primary reason that the set and dictionary data structures are so efficient in terms of the membership and retrieval operations.

In other words, hashability allows an object to be used as part of a set or dictionary because of the proper implementation of the discussed hash functions.

However, not all objects can be passed into the hash() function—only hashable objects. The condition on hashable objects is that they never change, have implemented the __hash__() method, and they can be compared to objects by implementing the dunder __eq__() method as well.

  • An object with implemented __hash__() method but not implemented __eq__() method is not hashable.
  • An object with implemented __eq__() method but not implemented __hash__() method is not hashable.
  • An object with implemented __hash__() and __eq__() methods is hashable.
  • An object with implemented __hash__() and __eq__() methods but that is mutable is not hashable. The reason is that mutability allows for a change of the objects data values which could result in a change of the return value of __hash__() which could break the code because it could lead to a behavior where an element is at one time part of the data structure and at another time not.

Furthermore, if two hashable objects have the same hash values as returned by the __hash__() method, they must also compare equal in regards to the __eq__() method.

How to Add an Element to a Set?

To add a hashable element to a set, call set.add(element). If the element is already a member of the set, the set doesn’t change.

>>> fruits = {'banana', 'apple'}
>>> fruits.add('strawberry')
>>> fruits
{'apple', 'banana', 'strawberry'}
>>> fruits.add('strawberry')
>>> fruits
{'apple', 'banana', 'strawberry'}

πŸ‘‰ Recommended Tutorial: How to Add Elements to a Python Set?

How to Add to an Empty Set in Python?

To add a hashable element to an empty set, call set.add(element).

>>> fruits = set()
>>> fruits.add('strawberry')
>>> fruits
{'strawberry'}

How to Add Multiple Elements to a Set?

To add multiple or all elements to a set that are stored in a given iterable, pass the iterable in the function set.update(iterable).

>>> fruits = {'apple', 'banana'}
>>> basket_to_add = ['strawberry', 'cocos']
>>> fruits.update(basket_to_add)
>>> fruits
{'apple', 'cocos', 'banana', 'strawberry'}

How to Add a List to a Set?

Given a set and a list. To add all list elements to a set, pass the iterable in the function set.update(iterable).

>>> fruits = {'apple', 'banana'}
>>> basket_to_add = ['strawberry', 'cocos']
>>> fruits.update(basket_to_add)
>>> fruits
{'apple', 'cocos', 'banana', 'strawberry'}

Python Set add() vs update()

The difference between set.add(element) and set.update(elements) is that the former adds a single element to a set and the latter adds multiple elements to a set.

In other words:

  • set.add() adds an element to this set.
  • set.update() adds all elements that are in any of the specified set arguments.

This code example shows both functions in action:

>>> fruits = {'apple', 'banana'}
>>> basket_to_add = ['strawberry', 'cocos']
>>> fruits.update(basket_to_add)
>>> fruits
{'apple', 'cocos', 'banana', 'strawberry'}
>>> fruits.add('berry')
>>> fruits
{'berry', 'strawberry', 'banana', 'apple', 'cocos'}

What is the Time Complexity of Set add()?

The runtime complexity of the set.add() function is O(1) because Python’s set data structure is implemented as a hash table and you can expect lookup, insert, and delete operations to have constant runtime complexity. However, this is only an average—from time to time you may run into collisions which could cause the runtime complexity to increase to O(n) due to the collision handling. On average, though, the runtime complexity of set.add() remains O(1).

You can see this in the following simple experiment where we run the set method multiple times for an increasing number of set elements.

What is the Time Complexity of Set add()?
Figure: Increasing the set size to up to 10 million elements doesn’t affect the runtime complexity. The graph shows a constant runtime complexity curve.

I ran this experiment on my Acer Aspire 5 notebook (I know) with Intel Core i7 (8th Gen) processor and 16GB of memory. Here’s the code of the experiment:

import matplotlib.pyplot as plt
import random
import time

sizes = [10**3, 10**4, 10**5, 10**6, 10**7]
runtimes = []

for size in sizes:
    s = set(range(size))

    # Start track time ...
    t1 = time.time()
    s.add(9999999999999)
    s.add(42)
    t2 = time.time()
    # ... end track time
    
    runtimes.append(t2-t1)


plt.plot(sizes, runtimes)
plt.ylabel('Runtime (s)')
plt.xlabel('Set Size')

plt.show()

Other Python Set Methods

All set methods are called on a given set. For example, if you created a set s = {1, 2, 3}, you’d call s.clear() to remove all elements of the set. We use the term “this set” to refer to the set on which the method is executed.

add()Add an element to this set
clear()Remove all elements from this set
copy()Create and return a flat copy of this set
difference()Create and return a new set containing all elements of this set except the ones in the given set arguments. The resulting set has at most as many elements as any other.
difference_update()Remove all elements from this set that are members of any of the given set arguments.
discard()Remove an element from this set if it is a member, otherwise do nothing.
intersection()Create and return a new set that contains all elements that are members of all sets: this and the specified as well. .
intersection_update()Removes all elements from this set that are not members in all other specified sets.
isdisjoint()Return True if no element from this set is a member of any other specified set. Sets are disjoint if and only if their intersection is the empty set.
issubset()Return True if all elements of this set are members of the specified set argument.
issuperset()Return True if all elements of the specified set argument are members of this set.
pop()Remove and return a random element from this set. If the set is empty, it’ll raise a KeyError.
remove()Remove and return a specific element from this set as defined in the argument. If the set doesn’t contain the element, it’ll raise a KeyError.
symmetric_difference()Return a new set with elements in either this set or the specified set argument, but not elements that are members of both.
symmetric_difference_update()Replace this set with the symmetric difference, i.e., elements in either this set or the specified set argument, but not elements that are members of both.
union()Create and return a new set with all elements that are in this set, or in any of the specified set arguments.
update()Update this set with all elements that are in this set, or in any of the specified set arguments. The resulting set has at least as many elements as any other.