- Python: How to add or append values to a set ?
- Add a single element to the set
- Adding a value to the set using add() function,
- Frequently Asked:
- Adding a duplicate element to the set
- Adding immutable objects to the set using add() function
- Adding a mutable object like list to the set will raise TypeError
- Adding multiple elements to the set
- Adding multiple values to the set using update() function
- Adding elements from multiple sequences to the set
- Adding dictionary keys to the set
- Adding dictionary values to the set
- Related posts:
- How to add an Element to a Set in Python
- Add an element to a Set using Add() method
- How to add multiple elements to a Set
- Adding objects to a set
- How to add a string as element to a set in Python
- Conclusion
- Related
- Recommended Python Training
Python: How to add or append values to a set ?
In this article we will discuss ways to add single or multiple elements to a set in python.
Add a single element to the set
Set in python provides a member function to append a single element to the set i.e.
It accepts an element as an argument and if that element is not already present in the set, then it adds that to the set. It returns nothing i.e. None. We can use this to add a single value to the set. Let’s understand this with an example,
Adding a value to the set using add() function,
# Initialize a set sample_set = # Add a single element in set sample_set.add(15) print(sample_set)
As 15 was not present in the set, so add() function appended that to the set.
Frequently Asked:
Adding a duplicate element to the set
As set contains only unique elements, so if try to add an element that already exist in the set, then it will have no effect. For example,
sample_set = # If element is already present the add() function will not do anything sample_set.add("Hello") print(sample_set)
As 15 was already present the set, so add() function did nothing with the set.
Adding immutable objects to the set using add() function
As Sets can only contain immutable elements, therefore we can add int, strings, bytes, frozen sets, tuples, or any other object that is immutable. For example, we can add a tuple to the set using add function,
sample_set = # Add a tuple in set sample_set.add((10, 20)) print(sample_set)
Tuple is an immutable object; therefore, it can be added to a set. Whereas list in python is a mutable object, so we cannot add a list to the python using add() function. If you try to pass a list object to the add() function, then it will give error. For example,
Adding a mutable object like list to the set will raise TypeError
sample_set = # Pass a list to add() will raise Error sample_set.add([21, 31])
TypeError: unhashable type: 'list'
So, we can use the set.add() function to add a single element to the set. What if we want to add multiple elements to the set in one line ?
Adding multiple elements to the set
Set in python provides another function update() to add the elements to the set i.e.
It expects a single or multiple iterable sequences as arguments and appends all the elements in these iterable sequences to the set. It returns nothing i.e. None. We are going to use this update() function to add multiple value to the set in a single line,
Adding multiple values to the set using update() function
Now we want to add 3 more numbers in the set i.e. 10, 20 and 30. Let’s see how to do that,
# Add multiple elements in set by passing them as a tuple sample_set.update((10, 20, 30)) print(sample_set)
We encapsulated all three elements in a tuple and passed that tuple as an argument to the update() function. Which iterated over all the elements in tuple and added them to the set one by one. Instead of passing a tuple, we can pass a list too i.e.
sample_set = # Add multiple elements in set by passing them in list sample_set.update(['a', 22, 23]) print(sample_set)
update() function will iterated over all the elements in passed list and add them to the set one by one.
Adding elements from multiple sequences to the set
In update() function we can pass multiple iterable sequences and it will add all the elements from all the sequences to the set. Let’s understand by an example,
Suppose we have some elements in different iterable sequences like,
list_1 = ['a', 22, 23] list_2 = [33, 34, 35] sampe_tuple = (31, 32)
Now we want to add all the elements in above two lists and a tuple to the set. We can do that using update() function,
sample_set = # Add multiple elements from different sequences to the set sample_set.update(list_1, sampe_tuple , list_2) print(sample_set)
We passed both the lists and the tuple to the update() function. It iterated over all of them and added all elements in them to the set.
Let see some more example of update() function,
Adding dictionary keys to the set
student_dict = sample_set = set() sample_set.update(student_dict) print(sample_set)
If we pass a dictionary to the update() function of set, then it will try to convert dictionary object to an iterable sequence. Dictionary will be implicitly converted to sequence of keys and update() function will add all the keys in the dictionary to the set.
Adding dictionary values to the set
student_dict = sample_set = set() sample_set.update(student_dict.values()) print(sample_set)
We passed a sequence of all values of the dictionary object to the update(). Which added them to the set. As set contains only unique elements, so now it contains only unique values of the dictionary. So, this is how we can add single or multiple elements in the set using add() or update() function.
The complete example is as follows,
def main(): # Initialize a set sample_set = print('Original Set:') print(sample_set) print('**** Add a single element to the set ****') # Add a single element in set sample_set.add(15) print('Set contents: ') print(sample_set) print('** Adding a duplicate element to the set **') sample_set = # If element is already present the add() function will not do anything sample_set.add("Hello") print('Set contents: ') print(sample_set) print('** Adding an immutable objects to the set **') sample_set = # Add a tuple in set sample_set.add((10, 20)) print('Set contents: ') print(sample_set) print('Adding a mutable object like list to the set will raise Error') # Can not pass a list object (mutable) to the add() function of set # sample_set.add([21, 31]) print('*** Adding multiple elements to the set ***') sample_set = # Add multiple elements in set by passing them as a tuple sample_set.update((10, 20, 30)) print('Set contents: ') print(sample_set) sample_set = # Add multiple elements in set by passing them in list sample_set.update(['a', 22, 23]) print('Set contents: ') print(sample_set) print('*** Adding elements from multiple sequences to the set ***') sample_set = list_1 = ['a', 22, 23] list_2 = [33, 34, 35] sampe_tuple = (31, 32) # Add multiple elements from different sequences to the set sample_set.update(list_1, sampe_tuple , list_2) print('Set contents: ') print(sample_set) print('*** Adding dictionary keys to the set ***') student_dict = sample_set = set() sample_set.update(student_dict) print(sample_set) print('*** Adding dictionary values to the set ***') sample_set = set() sample_set.update(student_dict.values()) print(sample_set) if __name__ == '__main__': main()
Original Set: **** Add a single element to the set **** Set contents: ** Adding a duplicate element to the set ** Set contents: ** Adding an immutable objects to the set ** Set contents: Adding a mutable object like list to the set will raise Error *** Adding multiple elements to the set *** Set contents: Set contents: *** Adding elements from multiple sequences to the set *** Set contents: *** Adding dictionary keys to the set *** *** Adding dictionary values to the set ***
Related posts:
How to add an Element to a Set in Python
Sets in python are used to store unique elements or objects. Unlike other data structures like tuples or lists, sets do not allow adding duplicate values to them. In this article, we will look at different ways to add an element to a set in python. We will also look at some of the use cases where we are not allowed to add specific types of objects to a set.
Add an element to a Set using Add() method
The add() method is used to add new values to a set. When invoked on a set, the add() method takes a single element to be added to the set as an input parameter and adds it to the set. When the input element is already present in the set, nothing happens. After successful execution, The add() method returns None.
We can add an element to a set using the add() method as follows.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) mySet.add(6) print("Set after adding 6 to it:", mySet)
Original Set is: Set after adding 6 to it:
When we add a duplicate element to the set, the set remains unchanged. You can see it in the following example.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) mySet.add(5) print("Set after adding 5 to it:", mySet)
Original Set is: Set after adding 5 to it:
How to add multiple elements to a Set
We will use the update() method to add multiple elements to a set. The update() method takes one or more iterable objects such as a python dictionary, tuple, list, or set and adds the elements of the iterable to the existing set.
We can add elements of a list to a set as follows.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myList = [6, 7, 8] print("List of values is:", myList) mySet.update(myList) print("Set after adding elements of myList:", mySet)
Original Set is: List of values is: [6, 7, 8] Set after adding elements of myList:
To add elements from two or more lists, we simply pass each list as an input argument to the update() method as follows.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myList1 = [6, 7, 8] myList2 = [9, 10] print("First List of values is:", myList1) print("Second List of values is:", myList2) mySet.update(myList1, myList2) print("Set after adding elements of myList1 and myList2 :", mySet)
Original Set is: First List of values is: [6, 7, 8] Second List of values is: [9, 10] Set after adding elements of myList1 and myList2 :
Just as lists, we can add elements from one or more tuples or sets using the same syntax which is used for lists.
When we try to add a python dictionary to a set using the update() method, only the keys of the dictionary are added to the set. This can be observed in the following example.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myDict = print("Dictionary is:", myDict) mySet.update(myDict) print("Set after updating :", mySet)
Original Set is: Dictionary is: Set after updating :
To add the values in a dictionary to the set, we will have to pass the list of values explicitly by using dict.values() method as follows.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myDict = print("Dictionary is:", myDict) mySet.update(myDict.values()) print("Set after updating :", mySet)
Original Set is: Dictionary is: Set after updating :
We can also use the unpacking operator * to add multiple elements to a set. For this, we will first unpack the current set and the object containing the elements which are to be added to the set. After unpacking, we can create a new set using all the elements as follows.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myList = [6, 7, 8] print("List of values is:", myList) mySet = print("Set after updating :", mySet)
Original Set is: List of values is: [6, 7, 8] Set after updating :
Adding objects to a set
Just like individual elements, we can also add objects to a set using the add() method. The only condition is that we can add only immutable objects. For example, we can add a tuple to a list using the add() method as follows.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myTuple = (6, 7, 8) print("List of values is:", myTuple) mySet.add(myTuple) print("Set after updating :", mySet)
Original Set is: List of values is: (6, 7, 8) Set after updating :
When we try to add a mutable object such as a list to the set, it raises TypeError. This is due to the reason that mutable objects are not hashable and cannot be added to the set.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myList = [6, 7, 8] print("List of values is:", myList) mySet.add(myList) print("Set after updating :", mySet)
Original Set is: List of values is: [6, 7, 8] Least distance of vertices from vertex 0 is: Traceback (most recent call last): File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 5, in mySet.add(myList) TypeError: unhashable type: 'list'
The TypeError can be handled by exception handling using python try except blocks.
How to add a string as element to a set in Python
We can add an entire string to a set using the add() method as follows.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myStr="PythonForBeginners" print("String is:", myStr) mySet.add(myStr) print("Set after updating :", mySet)
Original Set is: String is: PythonForBeginners Set after updating :
To add the characters of the string to the set, we will use the update() method as follows.
mySet = set([1, 2, 3, 4, 5]) print("Original Set is:", mySet) myStr="PythonForBeginners" print("String is:", myStr) mySet.update(myStr) print("Set after updating :", mySet)
Original Set is: String is: PythonForBeginners Set after updating :
Conclusion
In this article, we have seen various ways to add one or more elements to a set in python. We have also seen how we can add strings or other immutable objects to the set. Stay tuned for more informative articles.
Related
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.