add element to set in python

4 Easy Ways to Add Element to Set in Python?

In this blog post, we will discuss how to create a set in python and after that several options to add element to set in python. Feel free to skip the first part, if you already know how to create a set in python.

Before we understand different ways to add elements to python, Let’s refresh the below key points about the Python set.

  • Collection: It is used to store more than one data point
  • Unique Elements: Set doesn’t allow duplicate elements, at any time it will have only unique elements.
  • Unordered: Set doesn’t maintain any order while storing elements. We will not be getting elements in the order we add to the set.
  • UnIndexable: Unlike list, set elements are not accessible via indices. You can only do the membership test via the in operator.
  • Can store a variety of data: We can store ints, floats, and strings together in one set. We will not be able to add non-hashable types like the dict to the set.

How to create a set in python?

We can create a set in different ways in python based on the requirement or need. We have listed a few such ways below.

Method 1: Using the built-in set class

set is one of Python’s built-in classes. The set class constructor has an optional iterable parameter named seq.

If we don’t pass any parameter then it will create an empty set as below.

#not passing iterator to the constructor

movies = set()

print(movies)

#will print an empty set.
#output: set()

We could pass one of the iterator objects like a list, or tuple to the set class and create a non-empty set.

#passing list to set class constructor

movies = ['Black Panther: Wakanda Forever', 'Avatar',
          'Iron Man', 'Iron Man']

distinct_movies = set(movies)

print('movies:', distinct_movies)

#will print an set with distinct elements. Iron man will be there only once.

#output:
#movies: {'Iron Man', 'Black Panther: Wakanda Forever', 'Avatar'}

Method 2: With curly braces {}

We can create a set similar to a dict object as below.

movies = {'Iron Man', 'Black Panther: Wakanda Forever', 'Avatar'}

print(type(movies))

#output: <class 'set'>

Quick Summary:

Add to set – one element

To add one element to the set, you can use the set’s add() method.

  • Allowed element types: Hashable types like integer, float, string, etc.
  • Not allowed element types: Non-hashable types like list, set, and dict.

Add to set – multiple elements

As the add() does not accept collection types like a set, list, dict, etc, You have to look out for other options.

There are 4 below options to add multiple elements to a set. We have tested their performance with 10 million numbers. Following are the observations.

Fastest way

Using the union() method to add a set or a list to a set is the fastest way.

MethodTime Taken in MillisecondsMemory Usage In MB
Using union method190512
Using union operator198512
Using update method200512
Using for loop600384

Different ways to Add element to set in python

1. Add one element to set

You can add element to set in Python using the add() method. The set accepts adding mixed types of data points. You can add an integer, a float number, and a string to one set.

These are the 2 steps how the set add() method works.

  • Step 1: Check if an element already exists, exists returns -1, and does nothing.
  • Step 2: Add to set, it adds to element to set if doesn’t exist already.

To further understand add(), Please visit source code.

#initiated set with string type element
movies = {'Iron Man'}

#adding one more string element with add() method
movies.add('Black Panther: Wakanda Forever')

#adding one int element with add() method
movies.add(2022)

#movies set will have three elements
print(movies)

#output: {'Iron Man', 'Black Panther: Wakanda Forever', 2022}

2. Add a tuple to set

Similar to add element to set in Python, You can add a tuple to the set using the add() method only since the tuple is a hashable type.

#intiating a empty set
movies = set()

#adding one tuple element with add() method
movies.add(('Black Panther: Wakanda Forever', 'IronMan'))


#movies set will have one tuple element
print(movies)

#output: {('Black Panther: Wakanda Forever', 'IronMan')}

3. Add a list to set

We cannot add a list to the set using add() method because only hashable types can be added to the set via add() method.

  • Python’s list, set, and dict are not hashable types.

We can add a list to set using the below options.

Option 1: Use update() method

The Set’s update() method updates the current set with the union of itself and the input list. It won’t create a new set but updates the set itself.

#intiating a empty set
movies = set()

#adding a list of two elements with update() method
movies.update(['Black Panther: Wakanda Forever', 'IronMan'])

#movies set will have two elements
print(movies)

#output: {'IronMan', 'Black Panther: Wakanda Forever'}

Option 2: Using | operator

Another effective way to add element to set in Python is using pipe(|) operator. The | operator is used to get the union of two sets. The | operator creates a new set with the union of the current set an input set.

#intiating a empty set
movies = set()

#adding a list of two elements with | operator
movies |= set(['Black Panther: Wakanda Forever', 'IronMan'])

#movies set will have two elements
print(movies)

#output: {'IronMan', 'Black Panther: Wakanda Forever'}

Option 3: With the union() method

Another way to add element to set in Python is union() method. The union() method creates a new set with the union of itself and the input set.

#intiating a set with one element
movies = set(['Iron Man'])

new_movies = ['Black Panther: Wakanda Forever', 'Iron Man', 'Spider Man']

#adding a set of three elements with union() method
movies = movies.union(set(new_movies))

#movies set will have three unique elements
print(movies)

#output: {'Spider Man', 'Iron Man', 'Black Panther: Wakanda Forever'}

Option 4: Using for loop

We can add all list elements to set one by one by iterating through it with for loop.

#intiating a set with one element
movies = set(['Iron Man'])

new_movies = ['Black Panther: Wakanda Forever', 'Iron Man', 'Spider Man']

#adding new_movies elements to movies one by one
for new_movie in new_movies:
    movies.add(new_movie)

#movies set will have three unique elements
print(movies)

#output: {'Spider Man', 'Iron Man', 'Black Panther: Wakanda Forever'}

4. Add a set to another set

Adding a set to another set is identical to adding a list to a set. You can use all the above 4 methods.

  • Using update() method
  • Using | operator
  • Using union() method
  • Using for loop

How does set add() work internally?

Python’s set is based on Hashtable. To put it simply, HashTable is a list/bucket of linked lists and a hash function.

The following things on every add() method invoke:

  • Get the hash of the element that needs to be added
  • Based on the hash get the index of the bucket where a new element needs to be added
  • Add the new element to the bucket
Add Element to Set in Python - HashTable

Hope we are able to help you with add element to set in Python using different ways. If you are still facing any issues, let us know in the comment box. Follow codethreads.dev for more such insightful posts.

Frequently Asked Questions:

  • What is set() in python?

    set is a built-in class that supports different functions like add, update, remove, union, intersection, etc.

  • How to add element to set in Python?

    There are different ways to add element to set in Python. We have listed down 4 different ways with code examples in this guide.

  • Can you add objects to the set in python?

    Yes, we can add objects. When adding objects or custom types to set, better override __eq__, __ne__, and __hash__ methods.

  • Can we modify/update a set?

    Yes, we can. with the help of add() and remove() functions. But set is not indexable, so you will not be able to update with based on indices.

  • How do append to set Python?

    Python’s set does not support the append() method instead we can use add() method to append to set. Read the other methods to add multiple elements to set here.

Leave a Comment

Your email address will not be published. Required fields are marked *