Sets are mutable collection datatype in Python, which allows to add elements, update or change elements and delete or remove elements in the set objects. In this article, we will learn about various methods to add elements in Set.
In article Create Set in Python, we learned about various properties of Set collection datatype and also learned to create & access Set elements.
Add elements in Set
Set is an unordered, mutable, iterable collection datatype that can store heterogeneous elements. Set does not allow to store duplicate elements in it. We can use add()
and update()
functions to add elements into a Set.
add()
function is used to add single element at a time into the set.update()
function is used to add multiple elements (using list or tuple) at a time into the set.
Lets see various scenarios to add elements in Set using add()
and update()
function.
add()
function
Add elements in Set – Using Set in Python has built-in add()
function that can be used to add any datatype elements in Set.
# addition to set - using add method
print("addition to set - using add method")
courses = {'Python','AWS','Java','Azure','ML'}
print(courses)
courses.add('PHP') # add string element in set
courses.add(15) # add number element in set
courses.add(True) # add boolean element in set
courses.add(12.55) # add float element in set
print(courses) # print set with added elements
In this program, we have defined a Set referenced by a variable ‘courses’. We are using add()
function to add different datatype elements in this Set. Then we print Set with added elements.
Program Output
addition to set - using add method
{'Azure', 'Python', 'AWS', 'Java', 'ML'}
{True, 12.55, 'ML', 15, 'PHP', 'Azure', 'AWS', 'Java', 'Python'}
From the output, different datatype elements are added into the Set. Set being unordered collection datatype, elements printed are not in same order as it was in original Set.
Try adding duplicate element in Set
Set does not allow to store duplicate elements in it. When we try to add any duplicate element in Set, it neither add element into the set and neither it throws any error. It silently avoids the add operation for the given element.
# try adding duplicate element to set
print("try adding duplicate element to set")
courses = {'Python', 'AWS', 'Java', 'Azure', 'ML', 'PHP'} # 'PHP' already exists in Set
print(courses) # print elements of original set
courses.add('PHP') # try adding duplicate element 'PHP'
print(courses) # print elements of set after adding duplicate element
print("no addition of duplicate element")
In this program, we have defined a Set reference by variable ‘courses’. This set already has ‘PHP’ element. Using the add()
function we are adding the ‘PHP’ element into this set. Then we print the elements of the set.
Program Output
try adding duplicate element to set
{'PHP', 'Azure', 'Java', 'ML', 'AWS', 'Python'} # elements of original set
{'PHP', 'Azure', 'Java', 'ML', 'AWS', 'Python'} # elements of set after adding duplicate element
no addition of duplicate element
From the output, after adding ‘PHP’ element again, still we have same elements in the set. ‘PHP’ was not added again and no error was thrown from the program.
add()
method
Addition of Tuple to Set – using If we want to add Tuple elements into the Set, then this can not be achieved using the add()
method. add()
method added Tuple (a collection object) itself as an element of the Set. add()
method does not add Tuple elements as an element of the Set.
# addition of tuple to set - using add method
print("addition of tuple to set - using add method")
courses = {'Python','AWS','Java','Azure','ML'}
print(courses)
tuple = ('PHP', 'MongoDB') # defined Tuple
courses.add(tuple) # add tuple into set using add method
print(courses)
In this program, a Set is defined. We have defined a Tuple also. We are adding this tuple into the set using the add()
method. Then we are printing the update elements of the Set.
Program Output
addition of tuple to set - using add method
{'Java', 'AWS', 'Azure', 'ML', 'Python'}
{'Java', 'AWS', 'Azure', 'ML', 'Python', ('PHP', 'MongoDB')}
From the updated Set, Tuple (a collection object) was added as an element into the set. Tuple elements separately are not elements of the Set.
add()
method
Error – Addition of List to Set – using Set is an unordered collection datatype. It means there is no index for elements in Set. No index means, no hash generated for the stored elements in Set. But List is an ordered collection datatype, with index (as hash) generated for each element in List. Storing List into the Set creates conflict within collection properties, that is why Set does not allow to store List (a collection object) as an element. When we try to add list as an element to set, we got an error – TypeError: unhashable type: 'list'
# Error while adding list to set - using add method
print("Error while adding list to set - using add method")
courses = {'Python','AWS','Java','Azure','ML'}
print(courses)
course_list = ['PHP', 'MongoDB'] # defined List
courses.add(course_list) # add list into set using add method
A set is defined and referenced with a variable name ‘courses’. We have defined a List as well. We are adding this list into the set using the add()
method.
Program Output
Error while adding list to set - using add method
{'AWS', 'Azure', 'Python', 'ML', 'Java'}
Traceback (most recent call last):
File "D:\add-element-set.py", line 40, in <module>
courses.add(course_list)
TypeError: unhashable type: 'list'
From the output, we got an error – TypeError: unhashable type: 'list'
update()
method
Addition of Tuple elements to Set – using If we want to add Tuple elements into the Set, then this can be achieved using the update()
method. update()
method allow addition of Tuple elements into the Set. It is not like add()
method which added Tuple (a collection object) itself as an element of the Set.
# addition of tuple elements to set - using update method
print("addition of tuple elements to set - using update method")
courses = {'Python','AWS','Java','Azure','ML'}
print(courses)
tuple = ('PHP', 'MongoDB') # defined tuple
courses.update(tuple) # add tuple into set using update() method
print(courses)
In this program, we have defined a Tuple to add its elements into a Set. We are adding this tuple into the set using the update()
method. Then we are printing the updated elements of the Set.
Program Output
addition of tuple elements to set - using update method
{'Azure', 'ML', 'Java', 'AWS', 'Python'}
{'PHP', 'Azure', 'ML', 'MongoDB', 'Java', 'AWS', 'Python'}
From the updated Set, Tuple elements were added as elements of the set.
update()
method
Addition of List elements to Set – using Similar to Tuple elements, we can add List elements into the Set using the update()
method. update()
method allow addition of List elements into the Set.
# addition of list elements to set - using update method
print("addition of list elements to set - using update method")
courses = {'Python','AWS','Java','Azure','ML'}
print(courses)
course_list = ['PHP', 'MongoDB'] # defined list
courses.update(course_list) # add list into set using update() method
print(courses)
In this program, we have defined a List to add its elements into the Set. We are adding this list into the set using the update()
method. Then we are printing the updated elements of the Set.
Program Output
addition of list elements to set - using update method
{'Azure', 'ML', 'Java', 'AWS', 'Python'}
{'PHP', 'Azure', 'ML', 'MongoDB', 'Java', 'AWS', 'Python'}
From the updated Set, List elements were added as elements of the set.
Summary
In this article we learn about various scenarios to add elements into the Set. Following scenarios were explored:
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.
Python Topics
Interview Questions & Answers
Q: What is the time complexity of adding an element to a Set?
In Python, average time complexity of adding an element into a Set is O(1). This is because Sets in Python are implemented using hash tables, which allow for O(1) average constant time complexity for insertion operations.
In the worst-case scenario, where a hash collision occurs, the time complexity can degrade to O(n), where n
is the number of elements in the Set. But this is a rare situation due to Python’s efficient hash function design.
Q: Explain the hash tables design with Sets in Python?
Hash table is a data structure that maps keys to values using a hash function. In the context of Python sets, each element in the set is treated as a key in a hash table, with no associated value (since sets are just collections of unique elements).
- Hash Function – The hash function computes an integer (the hash code) from each element in the set. This hash code determines where the element is stored in the underlying array (bucket) of the hash table.
- Buckets – The hash table is an array of fixed size, where each slot in the array is referred to as a “bucket”. The hash code computed by the hash function determines which bucket an element will be placed in.
Q: Explain the concept of hash collision with Sets in Python?
Hash collision occurs when two different elements produce the same hash code and, therefore, map to the same bucket in the hash table. Python handles collisions using some techniques like:
- Open Addressing – If a bucket is occupied, Python looks for the next available slot in the sequential way until an empty slot is found.
- Chaining – Python can also use chaining, where each bucket stores a list or linked list of elements that hash to the same value.