Python Set (Part II)
smart and simple
In this article, we will learn functions in the set.
Set is a mutable object which means we can add or delete elements from the set.
There are some special functions in the set.
- union
- intersection
- difference
- difference_update
and many more.
The operation we have implemented in the 10th standard on the set can be performed using these functions.
let’s see one by one
Union simply returns all elements from both sets exactly once.
The intersection function returns only common elements.
It is just an (s1 - s2) operation. This function doesn't modify the original set.
difference_update is the same as the difference function but the change here is that it modifies the original set.
you can see set s1 got changed.
_________________________________________________________
let’s see some normal functions in the Set.
pop always deletes any random value from the set.
Application of this pop function is supposed, we have 100 students and we want to take viva of any random student, in that case, the pop function will be a great choice.
remove deletes the value which we have provided.
If I want to add a set of elements to another set then update is a great choice.
it similar to extends function in the list.
Can we create a tuple inside a set? If you don’t know about tuple, read my previous articles.
yes, it is possible to create a tuple inside a set.
Let’s try with a list……
we got an error here, but why?
because we have already seen in the last article that set stores elements according to the hash values.
a tuple is an immutable object that means id of tuple and hash value of tuple will not change again and again
while in the list we can add or delete elements and that will affect in the hash value. and it is not possible to change the location at runtime.
so set don’t allow us to use mutable object inside the set.
You can explore more functions in the set, just create a set then write the set name+. (dot)+TAB
try it yourself then your concepts will get more clear.
Thanks for reading !!