Thursday, August 26, 2021

Python for Beginners: 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)

Output:

Original Set is: {1, 2, 3, 4, 5}
Set after adding 6 to it: {1, 2, 3, 4, 5, 6}

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)

Output:

Original Set is: {1, 2, 3, 4, 5}
Set after adding 5 to it: {1, 2, 3, 4, 5}

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)

Output:

Original Set is: {1, 2, 3, 4, 5}
List of values is: [6, 7, 8]
Set after adding elements of myList: {1, 2, 3, 4, 5, 6, 7, 8}

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)

Output:

Original Set is: {1, 2, 3, 4, 5}
First List of values is: [6, 7, 8]
Second List of values is: [9, 10]
Set after adding elements of myList1 and myList2 : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

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 = {6: 36, 7: 49, 8: 64}
print("Dictionary is:", myDict)
mySet.update(myDict)
print("Set after updating :", mySet)

Output:

Original Set is: {1, 2, 3, 4, 5}
Dictionary is: {6: 36, 7: 49, 8: 64}
Set after updating : {1, 2, 3, 4, 5, 6, 7, 8}

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 = {6: 36, 7: 49, 8: 64}
print("Dictionary is:", myDict)
mySet.update(myDict.values())
print("Set after updating :", mySet)

Output:

Original Set is: {1, 2, 3, 4, 5}
Dictionary is: {6: 36, 7: 49, 8: 64}
Set after updating : {64, 1, 2, 3, 4, 5, 36, 49}

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 = {*mySet, *myList}
print("Set after updating :", mySet)

Output:

Original Set is: {1, 2, 3, 4, 5}
List of values is: [6, 7, 8]
Set after updating : {1, 2, 3, 4, 5, 6, 7, 8}

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)

Output:

Original Set is: {1, 2, 3, 4, 5}
List of values is: (6, 7, 8)
Set after updating : {1, 2, 3, 4, 5, (6, 7, 8)}

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)

Output:

Original Set is: {1, 2, 3, 4, 5}
List of values is: [6, 7, 8]
Least distance of vertices from vertex 0 is:
{0: 0, 1: 1, 2: 2, 3: 1, 4: 2, 5: 3}
Traceback (most recent call last):
  File "/home/aditya1117/PycharmProjects/pythonProject/string1.py", line 5, in <module>
    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)

Output:

Original Set is: {1, 2, 3, 4, 5}
String is: PythonForBeginners
Set after updating : {1, 2, 3, 4, 5, 'PythonForBeginners'}

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)

Output:

Original Set is: {1, 2, 3, 4, 5}
String is: PythonForBeginners
Set after updating : {1, 2, 3, 4, 5, 'P', 'y', 'F', 'r', 'g', 'B', 's', 'i', 'o', 'h', 'n', 't', 'e'}

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.

The post How to add an Element to a Set in Python appeared first on PythonForBeginners.com.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...