set add() Method - Python | Explained with Examples


Syntax -
set.add(element)

set is Required. This is the set in which the element will be added.
element is Required Input Parameter. This is the element that will be added to the set. Only one element can be passed. If more than one element is passed, the compiler will throw a TypeError.

set add() Method - Python

In Python, we can use the set add() method to add a given element to the set

If the element is already present in the set, then nothing is added to the set. The set remains unchanged or unmodified. The element is only added if the set we are dealing with doesn't have that element.

Here are some crucial points to remember when using Python's set add() method -

  • The input parameter is the element we pass to set add() method. It must be singular. If we pass more than one element as an input parameter, the compiler will throw a TypeError. We will be looking into it practically in Example 1.
  • The set add() method returns 'None', which means nothing.
  • The set add() method doesn't return a set when used to create a set object.
  • Once a set is created, we cannot alter its elements, but we can add new elements.
  • The set is an unordered collection, so elements that get added to the set can be in any order.
  • The runtime complexity of set add() method in Python is O(1), on average. Sometimes, due to Collision Handling, the runtime complexity may increase to O(n).

Let us look at the examples below for more clear understanding of the Python's set add() method.

Example 1 - Using set add()

In this example, we will look into the functionality of the set add() method. Also, we will see what is returned if we try to print the set add() method directly.

Here is the Python Code -

set_1 = {"name", "age", "city"}

print(set_1.add("gender"))  # Printing the return of set add() method
print(set_1)                # Printing the updated set_1

print('-'*10)

set_1.add("address")  # Adding an element to set_1 using set add() method
print(set_1)          # Printing the updated set


set_1.add('name')       # Passing an element that's present in the set
print(set_1)            # set_1 remains same

print('-'*10)

print(type(set_1))            # Printing the types of set_1
print(type(set_1.add('')))    # Printing the types of set add()

print('-'*10)

print(set_1)
set_1.add(12)
print(set_1)

print('-'*10)

set_1.add(11, 10)	# Passing two elements to set add() method throws TypeError
print(set_1)

The Output will be -

None
{'gender', 'name', 'city', 'age'}
----------
{'name', 'city', 'age', 'gender', 'address'}
{'name', 'city', 'age', 'gender', 'address'}
----------
<class 'set'>
<class 'NoneType'>
----------
{'', 'name', 'city', 'age', 'gender', 'address'}
{'', 'name', 12, 'city', 'age', 'gender', 'address'}
----------
line 28, TypeError: set.add() takes exactly one argument (2 given)

As we can see from the example above, if we try passing two elements to the set add() method, the compiler throws an unhashable TypeError, which means the set add() method in Python can only accept one parameter at a time.

Also, the set add() method in Python returns 'None', which means it doesn't return anything.

Example 2 - Using set add() with another set

Since the set in Python is of an unhashable type, we cannot directly use the set add() method to add one set to another.

To do so using the set add() method, we need to use any loop like for loop to iterate over each element in the other set.

Here is the Python Code -

set_1 = {"name", "age", "city"}

set_1.add(0.12)  # Adding a decimal element
print(set_1)

set_2 = {12, 23, 34}

for i in set_2:  # Adding elements of set_2 to set_1 using for loop
    set_1.add(i)

print(set_1)

print('-'*10)

set_3 = {'gender'}
set_1.add(set_3)
print(set_1)

The Output will be -

{'age', 0.12, 'name', 'city'}
{0.12, 34, 12, 'age', 23, 'city', 'name'}
----------
line 16, TypeError: unhashable type: 'set'

Example 3 - Using set add() with List

In this example, we will try to add elements from a list to a set using the set add() method.

Here is the Python Code -

set_1 = {"name", "age", "city"}

list_1 = [12, 23, 0.34]

for i in list_1:  # Adding elements of list_1 to set_1 using for loop
    set_1.add(i)

print(set_1)

print('-'*10)

list_2 = {'DOB'}
set_1.add(list_2)
print(set_1)

The Output will be -

{0.34, 12, 'city', 'age', 23, 'name'}
----------
line 13, TypeError: unhashable type: 'set'

Example 4 - Using set add() with Tuple

We can use the set add() method in Python to add the elements in the tuple to a set.

When there is more than one element inside a tuple, the whole tuple is added to the set and considered one element.

In the example below, we will understand this concept concisely.

set_1 = {"name", "age", "city"}

tuple_1 = ("DOB")
set_1.add(tuple_1)
print(set_1)

tuple_2 = ("DOB", "gender")
set_1.add(tuple_2)
print(set_1)

tuple_3 = ("name")
set_1.add(tuple_3)
print(set_1)

tuple_4 = ("name", "gender")
set_1.add(tuple_4)
print(set_1)

tuple_5 = (1, 2, 0.3)

for i in tuple_5:  # Adding elements of tuple_4 to set_1 using for loop
    set_1.add(i)

print(set_1)

The Output will be -

{'DOB', 'city', 'age', 'name'}
{'DOB', 'age', ('DOB', 'gender'), 'name', 'city'}
{'DOB', 'age', ('DOB', 'gender'), 'name', 'city'}
{'DOB', ('name', 'gender'), 'age', ('DOB', 'gender'), 'name', 'city'}
{0.3, 'DOB', ('name', 'gender'), 1, 2, 'age', ('DOB', 'gender'), 'name', 'city'}

Example 5 - Using set add() with Dictionary

We will use Python's set add() method with a dictionary in this example. The dictionary below denotes the collection of a person's coins from countries (some are repeated). We will print the number of countries whose coins the person possesses. 

Here is the Python Code -

coins_collected = {
    "USA": 45,
    "Canada": 21,
    "Germany": 85,
    "USA": 77,
    "France": 63,
    "Canada": 77,
}

countries = set()

for i in coins_collected.keys():
    countries.add(i)

print(countries)

The Output will be -

{'Canada', 'Germany', 'France', 'USA'}

Example 6 - Using update() instead of set add()

We can also use the update() method in Python instead of using for loop with the add() method to add elements of the list, tuple, or a set to another set.

Here is the Python Code -

set_1 = {"name", "age", "city"}

tuple_1 = ("DOB", "gender")
set_1.update(tuple_1)
print(set_1)

list_1 = ["Phone", "Email"]
set_1.update(list_1)
print(set_1)

set_2 = (123, 15)
set_1.update(set_2)
print(set_1)

The Output will be -

{'age', 'city', 'DOB', 'name', 'gender'}
{'8', 'age', '5', 'city', '7', 'DOB', 'name', 'gender'}
{'8', 'age', '5', 'city', '7', 'DOB', 'Phone', 'name', 'gender', 'Email'}
{'8', 'age', '5', 'city', '7', 'DOB', 'Phone', 15, 'name', 'gender', 'Email', 123}

The update() method should be used while adding elements from a list to a set

Be extra cautious while using the update() method with sets and tuples

  • If there is only one string in a tuple, list, or set, each letter will be iterated over and added separately to our set.
  • If there is only one element and that element is of a number or float type, the compiler will throw - TypeError.

Let's understand the code below to grasp the concept better.

Here is the Python Code -

set_1 = {"name", "age", "city"}

list_1 = [12]
set_1.update(list_1)
print(set_1)


list_2 = ["gender"]
set_1.update(list_2)
print(set_1)

tuple_1 = ("dob")
set_1.update(tuple_1)
print(set_1)

set_2 = ("0.90")
set_1.update(set_2)
print(set_1)

tuple_2 = (58)
set_1.update(tuple_2)
print(set_1)

The Output will be -

{'age', 'city', 12, 'name'}
{'city', 'gender', 12, 'age', 'name'}
{'b', 'd', 'city', 'gender', 12, 'age', 'o', 'name'}
{'b', 'd', '0', 'city', 'gender', 12, 'age', '.', '9', 'o', 'name'}
line 21, TypeError: 'int' object is not iterable

So, here are a few points to consider while adding elements to a set -

  • Utilize the set add() method to add a single item to a set.
  • Use the update() method to include elements from another set in the current set.
  • As a Set is an unordered collection, methods like the set add() or update() can add elements in any sequence.

This was all about using the set add() method in Python. I hope you found this article helpful.

set add() Method – Python Explained with Examples

You may like to Explore -

keys() Method – Python Dictionary | Explained with Examples

mode() method – Python statistics module

Python maketrans() string method – Explained with Examples

Cheers!

Happy Coding!

About the Author

This article was authored by Rawnak.