frozenset in Python

Frozensets similar to Sets are unordered collection of items, all elements are unique(no duplicates) but Frozensets are immutable while Sets are not. This is one of distinguishing factor between Sets and FrozenSets in Python. If in case your now aware of What are Sets in Python? or How to create Sets in Python? then see this Sets in Python Programming Language article.
Let’s jump straight into How to create Frozensets?

How to create FrozenSet?

Similar to set() function for creating simple sets, there does exist frozenset() method in Python for creating sets which are frozen.

  • Syntax for creating FrozenSet – frozenset(iterable)
  • Example showing creating of FrozenSet – frozenset([10, 29, 173, 92])

The statement frozenset([10, 29, 173, 92]) will create a frozenset {10, 29, 173, 92} which definitely will be immutable.

Examples of FrozenSets in Python

# FrozenSet created using list as iterable
set1 = frozenset([18, 92, 72])

# FrozenSet created using tuple as iterable
set2 = frozenset((28, 29, 182))

# FrozenSet created using Set as iterable
set3 = frozenset({ "Hello", "How are you" })

Accessing Elements inside a FrozenSet

Like Sets in Python, FrozenSets are also not subscriptable meaning you cannot use this frozeset[index] syntax for accessing elements inside it. So for seeing what’s inside a frozenset you need to use a For Loop.
Below is a code example showing How to access elements inside a FrozeSet using For Loop?

# Example

set1 = {29, 18, 891, 192}
for i in set1:
	print(i)

# this will print out
29
18
891
192

Differences between Set and FrozenSet in Python

  1. FrozenSets are immutable meaning values inside them cannot be changed, frozenset once created can never be changed while Sets are mutable.
  2. FrozenSets return error messages when functions like add(), clear() are called upon these, but Sets doesn’t rather these updates as per function.

FrozenSet Functions

Functions which can be applied to Sets in Python can also be applied to FrozenSets expect those functions which update set itself. As FrozenSet is immutable that’s why. For example – For set1 = frozenset({19, 27, 94}) doing set1.add(10) will raise AttributeError: ‘frozenset’ object has no attribute ‘add’ error.

Below is a list of Set Method which will raise AttributeError: ‘frozenset’ object has no addtribute error.

  • add() method
  • clear() method
  • discard() method
  • pop() method
  • remove() method

Below are some examples showing Calling of Set Functions or Set Methods on FrozenSets.

set1 = frozenset({19, 29, 183, 1278})
set2 = frozenset({193, 82, 13})

# Calling max() function on Frozenset
max(set1)             # Returns 1278

# Calling min() function on Frozenset
min(set1)             # Returns 19

# Calling len() function on Frozenset
len(set1)             # Returns 4

# Calling sorted() function on Frozenset
sorted(set1)          # Returns [19, 29, 183, 1278] list

# Calling sum() function on Frozenset
sun(set1)             # Returns 1509

# Calling .intersection() function on Frozensets
set1.intersection(set2)       # Returns frozenset() an empty frozenset

# Calling .union() function on Frozensets
set1.union(set2)              # Returns frozenset({193, 82, 19, 13, 183, 29, 1278})

# Calling .difference() function on Frozensets
set1.difference(set2)         # Returns frozenset({19, 29, 1278, 183})

# Calling .symmetric_difference() function on Frozensets
set1.symmetric_difference(set2)         # Returns frozenset({193, 13, 82, 19, 183, 29, 1278})

# Calling .isdisjoint() function on Frozensets
set1.isdisjoint(set2)                  # Returns True

# Calling .issubset() function on Frozensets
set1.issubset(set2)                    # Returns False

# Calling .issuperset() function on Frozensets
set1.issuperset(set2)                  # Returns False

Wait 🤷🏻 But what if I don’t know anything about Set Functions/Operations? Do Not Worry, I got you covered. 😁 See following articles to learn about Python Set Operations/Functions. Also keep in mind that functionality of these remain same for FrozenSets as well.

Operations on Sets in Python Programming Language
Built-in Python Functions which can be called upon Sets Data Structure

Converting FrozenSet to other Sequence Types

FrozenSets can be converted to other Python Sequence Types like tuples or lists or even to simple Python Sets.
For converting frozenSet to list/tuple/set you can use list(), tuple(), set() method respectively.
Below are some code examples showing How to convert FrozenSet to List, Tuple, Set.

set1 = frozenset({19, 83, 2672})

# Converting frozenset to list
list(set1)                     # Returns [19, 83, 2672] list

# Converting frozenset to tuple
tuple(set1)                    # Returns (19, 83, 2671) tuple

# Converting frozenset to Set
set(set1)                      # Returns simple Python set {19, 83, 2672}

Usefulness of FrozenSet

FrozenSet can be used as Key for Dictionary as FronSets are immutable and hashable so its content cannot be changed after its creation.
Below is a code example showing How Frozenset can be used as a Key in Python Dictionary?

set1 = frozenset({19, 28})
a_dict = { set1: "Hello" }
print(a_dict)            # Returns {frozenset({19, 28}): 'Hello'} a Python Dictionary

If in case, your not aware of What are Python Dictionaries? then see Dictionaries in Python Programming Language article.

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

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

Recent Posts