Learn Python Easy Way - Sets

Let us learn what a set is in Python. We use the term set in our language for example when I say, "I have a set of colours" that means I have a set of some colours that are unique, all different colors. Usually "a set" would denote a unique set of items, and that is how it is implemented in Python. The set in Python is used similar to the "Set Theory" in Mathematics. We can do operations like Union, Intersection, Difference on sets in Python.


We have learnt about Strings, Lists, Tuples and Dictionaries. We enclose Lists in [ ] Square brackets, Tuples in ( ) normal brackets, and dictionaries in { } Curly brackets.

The Sets in Python are enclosed in { } Curly brackets too. The difference in dictionaries and sets is that a dictionary is in key:value pair, whereas a Set is like a list of unique items.

The Sets can be created by using set([ ]) notation. This notation is useful if you want to create frozensets.

 One more thing about lists is that even if you type duplicate elements in a Set it will automaticlly be discarded.

Let us create a Set using { } Curly brackets

fruits = {"Apples","Bananas","Lemons","Pineapples","Watermelons","Grapes","Pears","Dates","Pomegranates"}

This is a Set of names of different fruits. I have used "" double quotes for strings, you can use single quotes instead if you like.

Now let us create a set of names of dry fruits
dry_fruits = {"Almonds","Cashews","Dates"}

And a set of Citrus fruits
citrus_fruits = {"Lemons","Pineapples"}

If you know how Sets in Mathematics are handled, the same principles are applied here. The idea of a Superset and a subset is also applied here

We can determine if a given set is a subset of another with issubset() function

dry_fruits.issubset(fruits)

This will check if the set dry_fruits is a proper subset of fruits or not. If all the items in dry_fruits are present in the set fruits then it will return True, or it will say False

Here in our case we see False returned, because the items "Cashews" and "Almonds" are not present in the set fruits.

Now Let us check the other list

citrus_fruits.issubset(fruits)

This will return True as all the elements of citrus_fruits are present in the set fruits as well.

We can add things to a list after it has been created.

fruits.add("Guava")

Will add a new name "Guava" in the fruits set

Another set operation is difference, we can find out the unique elements in the first set that are not present in the other set

dry_fruits.difference(fruits)
{'Almonds', 'Cashews'}

fruits.difference(dry_fruits)
{'Apples', 'Pears', 'Bananas', 'Watermelons', 'Pomegranates', 'Grapes', 'Pineapples', 'Lemons'}

We can also do this operation with more than one sets

fruits.difference(dry_fruits).difference(citrus_fruits)

Will display only the items from fruits that are not present in either dry_fruits and citrus_fruits


There is a function called difference_update

fruits.difference_update(dry_fruits)

That will remove all the items that are common to both the sets from the fruits set

We can use the Union operator on sets too, it is non destructive operation, does not make any changes to the sets themselves

fruits.union(dry_fruits)
or
fruits | dry_fruits

There is  function called intersection, it will display only those elements that are present in both the sets

x = {5, 3, 4, 2, 6}
y = {5, 1, 11, 9, 2}

x.intersection(y) wil return
{2, 5}


So we can run functions that change the items in the sets as well as there are functions that operate without making any changes.

What if we do not want any changes to happen in our sets. Could we do that? The answer is Yes, we can create a Set such that it can not be altered later on. It is called frozen set

You could create a set using this notation

weekdays = set(["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"])

Now let us create a frozen set

weekdays = frozenset(["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"])

Now try to remove an element from the frozen set

weekdays.remove("Monday")

you will see an error
AttributeError: 'frozenset' object has no attribute 'remove'

So that is how we can make our sets write protected. We can read them like  normal sets.