Inspecting Frozenset In Python

Introduction

Most of the Iterables in Python are mutable in nature like List, Set, Dictionaries. An Immutable object always remains in one state that’s why they are thread-safe in nature and its state cannot be modified by multiple threads. With Immutable objects, the code is more readable and maintainable and even it’s easier to write tests as the state will not be changed.

The article explains in detail with examples one of the functions in Python ‘frozenset’ which accepts an Iterable as a parameter and transforms it to an Immutable object. Once the Iterable of any kind like list, set, the dictionary is passed to frozenset after that element cannot be added or removed from the frozenset object.

A few side effects of using frozenset are,

  1. The ordering is not guaranteed, like a list is an ordered collection but after frozenset the order of elements in a list can change
  2. If the Iterable contains duplicate elements after frozenset duplicate elements will be eliminated.
  3. The frozenset function returns an Immutable version of frozenset object with elements of Iterable, if no parameter is passed then an empty frozenset will be returned.

Syntax

frozenset( [ Iterable ])

Examples

List, set and dictionary examples will be covered in this section. Let’s understand by a simple List example

numbers = [1,2, 3,4,5]
f_list = frozenset(numbers)

print(type(f_list))
print(f_list)

# <class 'frozenset'>
# frozenset({1, 2, 3, 4, 5})

If no parameter is passed to the frozenset an empty frozenset object will be returned

f_list = frozenset()
print(type(f_list))
result

# <class 'frozenset'>
# frozenset()

List with duplicate elements,

numbers = [1,2,2,3,4,5]
f_list = frozenset(numbers)
print(type(f_list))
print(f_list)

# <class 'frozenset'>
# frozenset({1, 2, 3, 4, 5})

The duplicate elements will be eliminated.

Example 2

Trying to add or remove elements from frozenset, TypeError will be thrown

numbers = [1,2,3,4,5]
f_list = frozenset(numbers)
f_list [5] = 6

Set Example

The behavior of frozenset is the same with every iterable.

s = {1,2,3,4,5,2}
print(s)

f_set = frozenset(s)
f_set

Dictionary Example

The frozenset in the dictionary will be used on keys

dict = {"name" : "Sam", "age" : 32, "dept" : "IT"}
print(dict)
f_dict = frozenset(dict)
print(f_dict)

Frozenset Comparison

The frozenset can be compared for equality, checking for subsets and superset comparisons.

f_list1 = [1,2,3,4]
f_list2 = [1,2,3,4]

print(f_list1 == f_list2) # True

f_list1 = [1,2,3]
f_list2 = [1,2,3,4]

print(f_list1 < f_list2) # True

f_list1 = [1,2,3]
f_list2 = [1,2,3,4]

print(f_list1 > f_list2) # False

Summary

The article explains the basics of Frozenset with examples of List, Set, and Dictionary. Along with that also explained the frozenset comparison.


Similar Articles