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.
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.
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.
- Identify unique elements from a collection of elements containing duplicates.
- Can verify common elements between two collections.
- Can check if two unsorted collections are equal.
- Can verify if two collections are equal and if not can identify the difference from either of the sets.
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/