Day #32 - Set Methods

Day #32 - Set Methods

Β·

6 min read

Introduction

Welcome to my 32nd blog post. In the last blog, I learned about the concept of sets in python. In this blog, I went into details of the methods on sets in python and understood what all different operations can be performed on sets as a datatype. I also wrote some good code and practised a good number of problems on sets. Let's dive into more details.

So let's get started......

Joining sets

Sets in python work in a similar fashion as they work in traditional mathematics. Operations like union and intersection on the sets are common just like in mathematics.

union() and update():

The union() and update() methods print all items that are present in the two sets.

The union() method returns a new set whereas the update() method adds an item to the existing set from another set.

Example -

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.union(cities2)
print(cities3)

Output -

{'Tokyo', 'Madrid', 'Kabul', 'Seoul', 'Berlin', 'Delhi'}

Example -

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.update(cities2)
print(cities)

Output -

{'Berlin', 'Madrid', 'Tokyo', 'Delhi', 'Kabul', 'Seoul'}

intersection and intersection_update():

The intersection() and intersection_update() methods prints only items that are similar to both sets.

The intersection() method returns a new set whereas intersection_update() method updates into the existing set from another set.

example -

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.intersection(cities2)
print(cities3)
{'Madrid', 'Tokyo'}

Example -

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.intersection_update(cities2)
print(cities)
{'Tokyo', 'Madrid'}

symmetric_difference and symmetric_difference_update():

The symmetric_difference() and symmetric_difference_update() methods print only items that are not similar to both sets.

The symmetric_difference() method returns a new set whereas the symmetric_difference_update() method updates into the existing set from another set.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.symmetric_difference(cities2)
print(cities3)

Output -

{'Seoul', 'Kabul', 'Berlin', 'Delhi'}

Example -

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.symmetric_difference_update(cities2)
print(cities)
{'Kabul', 'Delhi', 'Berlin', 'Seoul'}

difference() and difference_update():

The difference() and difference_update() methods prints only items that are only present in the original set and not in both the sets.

The difference() method returns a new set whereas difference_update() method updates into the existing set from another set.

Example -

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
cities3 = cities.difference(cities2)
print(cities3)

Output -

{'Tokyo', 'Madrid', 'Berlin'}

Set Methods

isdisjoint()

checks if items of a given set are present in another set. This method returns False if items are present, else it returns True.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
print(cities.isdisjoint(cities2))
False

issuperset():

checks if all the items of a particular set are present in the original set. It returns True if all the items are present, else it returns False.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul"}
print(cities.issuperset(cities2))
cities3 = {"Seoul", "Madrid","Kabul"}
print(cities.issuperset(cities3))

issubset():

checks if all the items of the original set are present in the particular set. It returns True if all the items are present, else it returns False.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Delhi", "Madrid"}
print(cities2.issubset(cities))
True

add():

If you want to add a single item to the set use the add() method.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.add("Helsinki")
print(cities)

update():

If you want to add more than one item, simply create another set or any other iterable object(list, tuple, dictionary), and use the update() method to add it into the existing set.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Helsinki", "Warsaw", "Seoul"}
cities.update(cities2)
print(cities)

remove()/discard()

We can use remove() and discard() methods to remove items form list.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Tokyo")
print(cities)

Note: -

The main difference between remove and discard is that, if we try to delete an item which is not present in set, then remove() raises an error, whereas discard() does not raise any error.

Example -

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.remove("Seoul")
print(cities)
KeyError: 'Seoul'

pop()

This method removes the last item of the set but the catch is that we don’t know which item gets popped as sets are unordered. However, you can access the popped item if you assign the pop() method to a variable.

Example -

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
item = cities.pop()
print(cities)
print(item)
{'Tokyo', 'Delhi', 'Berlin'} Madrid

del - del is not a method, rather it is a keyword which deletes the set entirely.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
del cities
print(cities)
NameError: name 'cities' is not defined

Note: - We get an error because our entire set has been deleted and there is no variable called cities which contains a set.

clear():

What if we don’t want to delete the entire set, we just want to delete all items within that set? This method clears all items in the set and prints an empty set.

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities.clear()
print(cities)
set()

Check if item exists in set()

You can also check if an item exists in the set or not.

info = {"Carla", 19, False, 5.9}
if "Carla" in info:
    print("Carla is present.")
else:
    print("Carla is absent.")
Carla is present.

Resources Used

You can watch the video of Day#32 by clicking on the below link πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡πŸ‘‡

Conclusion

Thanks, guys for going through this blog post. We wrote a good bunch of code to understand every function method of the set in much greater detail. Though a set as a datatype can be a bit difficult to understand for a beginner with non-math background, an understanding of sets will be of help in many coding problems in future.

Thank you if you read this post and have found this post useful. I hope you have joined me and are enjoying my magical journey of python coding. This is it for Day #32

See you in the next one.....


About Me

Hey Guys, I am Chintan Jain from CodeWithJain. I am a trader and content creator. I am also passionate about tech and hence wanted to explore the field of tech. I always wanted to learn to code so I watched many tutorials but procrastinated practicing coding. To get into the habit of coding consistently I am starting to BLOG with HASHNODE on daily basis.

I will document my coding journey from scratch and share my daily learnings in a blog post on HASHNODE. I hope you all will enjoy my content and my coding journey.

So what are you waiting for, smash the FOLLOW and LIKE buttons and follow along my coding journey, a step to create more beautiful digital products and empower people.


Β