Sets the Maths one — Python

Image for post

Sets are mutable data type objects containing a collection of elements. It is an unordered collection and contains only unique objects in it. Being an unordered data structure it will not record element position or the order elements are inserted into it.

The other name for sets are Value-less dictionaries and they are internally implemented as dictionaries. In fact, you can imagine set elements as keys of dictionaries and since dictionary keys cannot have mutable data objects. The same requirement applies to set elements as well. Please refer to my other post to understand more on dictionary keys — 

Even though sets are mutable it can have only immutable elements. It will not allow any mutable object as an element of it. This means sets cannot have lists, dictionaries and sets itself because they are mutable data structures. Below are some of the examples depicting the same.

Image for post
Example showing type of elements Set can hold

github link: https://github.com/bvvkrishna/Deep-Dive-into-Python/blob/master/Mutable%20Set%20Example.ipynb

Empty Sets can be created only by using the set() constructor function rather than symbolic notation {}. Using symbolic notation will create a dictionary because sets and dictionaries both use the same symbol for creating their data structures. Below is an example showing the same.

Image for post
Example to create an empty Set

github link: https://github.com/bvvkrishna/Deep-Dive-into-Python/blob/master/Creating%20Empty%20Set.ipynb

Sets have multiple applications other than identifying unique elements from a collection of elements containing duplicates. The following are the applications and below are examples depicting the same.

  1. Identify unique elements from a collection of elements containing duplicates.
  2. Can verify common elements between two collections.
  3. Can check if two unsorted collections are equal.
  4. Can verify if two collections are equal and if not can identify the difference from either of the sets.
Image for post
Set Applications

github link: https://github.com/bvvkrishna/Deep-Dive-into-Python/blob/master/Set%20Applications.ipynb

For deep dive on Python internals follow me on Linkedin –https://www.linkedin.com/in/krishnabvv/