Sets in Python

Sets

Sets are unordered, lists of elements which are unique and duplicate elements are not allowed. A set can be modified, but the elements contained in the set must be of an immutable type, such as list, string or tuple.

How to write a set?

Sets can be written using two types.

  • Using set () function.
  • Using curly braces.

Let’s check them one by one. First create a set using set () function.

I have passed a list in the set function. Once set is created you check the datatype using the type command. I have also created the list to differentiate among the two.

This time I have created another set from a tuple list. Both list and tuple are immutable. Let’s check for strings also.

OK. After creating a set, let’s check the output of the set. 

The output of the set is like a list. A better comparison can be done with the list itself.

Now one can observe the difference. Set has no elements repeated, not even space. And the elements are arranged unordered. A list has an ordered set of repeated elements.

Now, let’s create a set by using another method: Using the curly braces.

Simply using curly braces without writing set commands will convert the given entity into a set. But what about an empty curly bracket?

Now this is the thing to remember. An empty curly brace returns the dictionary. The only way to describe an empty set is using set () function.

Operations on Set

The length of the set can be calculated using len () function. 

The membership operators in and not in works with sets as well.

Union in Sets

Two sets can be joined together using union function, or by using β€œ | ” sign. Let’s check.

That’s good. OK. One thing again is observable. The elements are arranged unordered. Here, one task you can perform is to check the final set when both these sets have any name common, say, Nebula. 

A question can come in mind that are union and β€œ | ” the same thing? (I know this question never came to mind. But now, it has been). Now this is an important topic to discuss. This union is a method and β€œ | β€œ is an operator. It’s an interview question actually which asks are method and operator the same thing? We just checked this thing by code. Let’s do some more coding.

Did you notice the concept? OK. Let’s first see what we have done. We are joining a set with a tuple. In the first code, an error occurred that this is an unsupported operation for set and tuple. In the second code, union makes it a supported argument. That’s why, I planted this question in your mind that are union and β€œ | ” the same thing? There is a slight difference in method and operator function. The union () method converts the argument into a set and then performs the union operation. Union allows multiple set operations. It means that there can be union in more than two sets.

Intersection in Sets

This function will return those values which are common in all sets. Similar to union, the method used here is intersection and the operator is & operator.

The code is self-explanatory I guess. But yes, you can try the operator vs method issue here also. Intersection allows multiple set operations.

Difference in Sets

This function will return those values which are present in one set but not present in another set. Similar to union, the method used here is difference and the operator is the operator.

The set hero_name has elements which are not present in set non_hero_name. Difference allows multiple set operations.

Symmetric Difference in Sets

This function will return those values which are present in either the first set or second set but not in both sets. Or the common element is not displayed. Similar to union, the method used here is symmetric_difference and the operator is β€˜ ^ β€˜ operator.

This function also allows multiple set operations. But there is one interesting thing. The β€˜ ^ β€˜ operator allows multiple sets, the .symmetric_difference () method doesn’t allow multiple sets.

.isdisjoint () in Sets

The function is used to check whether or not the sets have any elements in common. If there are no common elements then, True is returned.

.issubset () in Sets

The function is used to check whether one set is a subset of the other. The β€œ <= β€œ is used to check the subset.

We can see that both sets have some common elements. Therefore, the disjoint value is False. And we can say that they are a subset of each other. If both sets have no elements in common, then they are empty sets.

Both sets have nothing in common. Thus heroes and villains form an empty set.

Proper subset () in Sets

The function is used to check whether one set is the proper subset of the other. The word proper means every element of one set is in another set but both sets are not identical. The β€œ < β€œ is used to check the proper subset.

You can see that every element of the first set is not present in the second set. Therefore, the output returned is False.

.issuperset () in Sets

The function is used to check whether one set is a superset of the other. It is an opposite function of the subset. It checks whether all elements of one set are also present in another set. The β€œ>= β€œis used to check the superset.

The set avengers contain all elements of set heros, therefore, heros is a superset of avengers and the output returned is True. But set heros don’t contain all the elements of set avengers. Thus, the output returned is False.

Proper superset () in Sets

The function is used to check whether one set is the proper subset of the other. The word proper means every element of one set is in another set but both sets are not identical. The β€œ> β€œis used to check the proper subset.

Can you check to see whether a set is subset, superset, proper subset and proper superset of its own? 

Moving on to modifying a set. There are many ways to modify a set.

.add () in Sets

The function is used to add any element (single immutable element).

What if we add more than one element?

Look at the error statement in the last line. Add () takes only one element. But we are giving it two. 

To remove any element from the set, there are two ways to do so: .remove() and .discard().

The difference is seen when we try to remove any element which is not present in the set.

When we try to remove any non-existing element from a set using remove () method, it will throw an error. On the other hand, using discard () will not give an error. It will simply return the existing set. 

Another way to remove any element is using the .pop () method. But this method randomly removes any element.

One can see how pop () removes any random element from the set. It is also important to see the last example. When pop () is applied on an empty set, an error is thrown back.

Another important function is .clear () function. This is used to .clear () the set.

Augmented Assignment Operators and Methods

Union, intersection, difference, and symmetric difference operators mentioned above have an augmented assignment form and they can be used to modify a set. There is a method for each augmented assignment operator as well.

a.update (b) or a |= b : This will add those elements of b to a, which are not present in set a, and then update the set a.

a.intersection_update(b) or a &= b [ &c… ] : This will retain only those elements of b and  a, which are common in both the sets and then update the set a.

a.difference_update(b) or a -= b [ |c… ] : This will remove those elements of b which are common with a, and then update the set a.

a.symmetric_difference_update(b) or a ^= b [ |c… ] : This will retain those elements which are either present in the set a or b, but not in both the sets, and then update the set a.

Frozen Sets

As the name suggests, sets which are immutable or cannot change are called frozen sets. To make a set frozen, the frozenset command is used.

Non- modifying operations can be performed on frozensets but modifying by methods fail. Let’s see.

Clearly it can be observed that, frozenset has no attributes of pop, clear or add.

Python does not perform augmented operations either on frozen sets. Instead of modifying the original set, it reassigns the set variable to a new object.

You can see that when we check the identity of set a, it’s different. Set a is reassigned and the original reference of a is now vanished.

If there are sets whose elements are also sets, then they cannot be combined to make a new set, because set elements must have to be immutable. If you try to make a set of sets whose elements are also sets, an error will occur.

But still if you want to create a set of sets, this can be achieved by a frozen set. A dictionary key is also immutable like sets but sets can’t be used as keys.

Again, the frozen set is the saviour.

The final topic will be making a Set Comprehension. It’s very easy. Let’s make a list of integers and we will find the square of each digit in this list. Now sets remove duplicates. I’ll make a list of duplicate elements. Let me check if it removes the duplicates as well as generate the square value. The statement is exactly equal to the list, except that the brackets are curly brackets. We use curly braces in dictionary comprehension also. But there we will have a key:value pair as well.

This is all about sets.

Design a site like this with WordPress.com
Get started