Python types of sets -set and frozenset

There are two types of sets in Python :set and frozenset.In this post we will discuss the frozenset(the set type is discussed in another post link here:set.The frozen set is created using only the method frozenset().If you do not use this method and simply use the curly braces without any method then the set created is not frozenset.But rather the other type set.

>>> st={ 23 ,45 ,'New' } #set created
>>> sf=frozenset( {'kap' , 45.67 , "text"} ) #frozenset created
>>> #to check the set type use the method type()
>>> type( st )
<class 'set'>
>>> type( sf )
<class 'frozenset'>

Calling the method type() gives their respective type and you can see the type inside the quotation.

Like any set the frozenset does not allow duplicate elements.

>>> sf=frozenset( {"New" , 89 , 'po' , 12 , 90.34 , 'New' , 12.0 , 45 } )
>>> sf
frozenset({'po', 90.34, 'New', 89, 12, 45}) #no duplicate elements

Difference between set and frozenset

The main difference between set and frozenset is set is mutable while frozenset is immutable.The mutability and immutability of the two set type depend on the how the elements can be changed or not.For instance the in set type we can remove or add any extra elements we want.However, this is not allowed in frozenset.

To remove an element from set we use the method remove() and to add element we use add().

>>> #testing adding element
>>> st={'happy' , 'new' , 'text' , 90 , 274.456}
>>> sf=frozenset( { 45 ,89 ,90.45 , "Candcpluplus.com is the best"} )
>>> st.add( '78' ) #work fine
>>> st
{'happy', '78', 'new', 'text', 274.456, 90}
>>> sf=frozenset.add( 'New' ) #we cannot add element
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    sf.add( 'Name' )
AttributeError: 'frozenset' object has no attribute 'add' 
>>> #testing remove element
>>> st.remove( 'happy' ) #work fine
>>> st
{'78', 'new', 'text', 274.456, 90}
>>> sf.remove( 89 ) #we cannot remove element
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    sf.remove( 89 )
AttributeError: 'frozenset' object has no attribute 'remove'

I am sure the example above has made very clear that once the frozenset object is created they cannot be manipulated in any way.

Although frozenset set are immutable operation like union,intersection,difference and symmetric difference is till allowed.

>>> sf1=frozenset( {23 ,45 ,78 , 90 , 'New'} )
>>> sf2=frozenset( { 23, 30 , 910 , 90 , 'text'} )
>>> sf1 | sf2 #union
frozenset({45, 78, 910, 'text', 'New', 23, 90, 30})
>>> sf1 ^ sf2 #symmetric difference
frozenset({30, 'New', 78, 45, 910, 'text'}) 

The frozenset are quite limited in comparison to set but they however prove useful for performing operation like union,difference,intersection,etc.



Leave a Reply

Your email address will not be published. Required fields are marked *