Python provides set and frozenset Set Types to deal with unordered, unique (no duplicates) collections. Even though both of these are Set Types, there is a clear difference between them.
sets are mutable whereas frozensets are immutable objects. That means, we can add or remove the elements in sets whereas frozensets doesn’t allow to modify once those are created.
Creating Sets – Using set and frozenset constructors
The constructor set is used to create the sets. And the constructor frozenset is used to create the frozensets. Both these constructors takes a single or no argument. If no argument is passed, these will create empty sets; sets with zero elements.
>>> st = set() >>> st set() >>> fst = frozenset() >>> fst frozenset()
We create the Sets with ONLY hashable objects. Why is it so? This is because; as I mentioned above, Sets are the collections of unique elements. Duplicate entries are NOT allowed in Sets. This is achieved by using unique hash values to the objects in the Sets. That means objects in Sets are hashable.
If Sets allowed mutable objects (no hash value); which allows to modify the elements and cause to have repetitive elements. This way we cannot maintain the uniqueness. This is the reason, Sets accepts ONLY immutable objects, which are hashable.
Creating a set using curly braces
We can use curly braces to create the sets. Each element should be separated by a comma (“,”). This is an alternate approach to create the sets (NOT for frozensets). Here is an example: Note that, Sets are unordered; so you see the elements are added without any order.
>>> st = {"A", "B", "C"}
>>> st
{'C', 'A', 'B'}
>>>As mentioned above sets accept only hashable (or immutable) objects. Let’s try to add mutable objects, and you will see below error:
>>> st = set({[1, 2, 3], ["A", "B", "C"]})
Traceback (most recent call last):
File "", line 1, in
st = set({[1, 2, 3], ["A", "B", "C"]})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unhashable type: 'list'
>>>
This clearly tells that, sets are mutable objects, but its’ elements are immutable. We can add or remove elements to and from sets, but we can’t update its’ elements. You can’t put lists or dictionaries inside a set.
Also, if you want to put sets inside the set, the inside sets must be a frozensets. Otherwise, you will get below error:
TypeError: unhashable type: 'set'Accessing elements from the Sets
Sets don’t support indexing or slicing. This is because, sets have unordered elements. There is no meaning to maintain indexing. To fetch the elements from sets, we can use for to iterate through the elements in the sets. Both sets and frozensets supports this. Here is the simple example to fetch the elements from the sets:
>>> for ele in st: ... print(ele) ... C A B >>>
Modifying Sets – Adding and Removing elements
Sets have add and remove methods to allow to modify the sets. Below example, will add an element 10 and remove it from the set.
>>> st.add(10)
>>> st
{'C', 'A', 10, 'B'}
>>> st.remove(10)
>>> st
{'C', 'A', 'B'}When you are attempting to remove an element which does not exist in the set, Python throws a KeyError. Below example shows this:
>>> st.remove(400)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 400
>>>As frozensets are immutable, we can’t modify the frozensets once these are created. So, add and remove methods do not exist for frozensets.
>>> fst = frozenset(("Apple", "Banana", "Cherry"))
>>> fst
frozenset({'Banana', 'Cherry', 'Apple'})
>>> fst.add("Date")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>>Creating Subsets
Yes, it is possible to create a set within the set. The only condition here is the subset must be a frozenset. Because frozensets are immutable. As mentioned above, sets accept ONLY hashable objects. Lets’ take a simple example to clarify how to create a set within a set.
>>> st_in_set = set({frozenset({1, 2, 3}), frozenset({10, 11, 12}), frozenset({"Apple", "Banana", "Cherry"})})
>>> for subset in st_in_set:
... print(subset)
...
frozenset({1, 2, 3})
frozenset({'Cherry', 'Banana', 'Apple'})
frozenset({10, 11, 12})
We discuss more on Python in my upcoming Articles.
/Shijit/
The Best Explanation of Sets. Thanks a lot!