What is Python Frozenset?

It is an inbuilt Python function that takes an iterable object as the input making them immutable. It halts the iterable objects and makes them immutable.

So its contents cannot be changed after its creation. And it offers all the functionalities that a set provides in Python.

Frozenset in Python 3

Frozen sets in Python are a native data type that possesses the qualities of sets— (including class methods) but are immutable like tuples.

The main reason to use them is to write more clean and efficient code. By defining a variable as a frozen set, we are telling future coders not to modify this.

Frozenset vs Set Python

Here we are going to discuss the differences between frozenset and set in Python 3.

A set is said to be an unordered list of data types that are iterable, mutable, and we don’t have to copy items. We use a set (and not a list) because these methods are highly enhanced to check if a particular item is present in the set or not.

On the other hand, the frozenset is just an immutable category of a Python set object.

In Python sets, we can change the items whenever needed, whereas items of the frozenset stay the same once created. Due to this reason, frozen sets are used as a key in Dictionary.

Syntax:

The syntax for frozenset in python is very simple. It is:

frozenset(iterable)

Or, we can also write it as:

class frozenset([iterable])

The method returns a new frozenset object, whose elements are taken from the passed iterable. If the iterable is not specified, a new empty set is returned.

Note: When nothing is properly specified, the frozenset() method returns an empty frozenset object.

For example,

vowels = ('a', 'e', 'i', 'o', 'u')  
fs = frozenset(vowels)  
print('The vowels are:', fs)  
print('Empty frozen set is:', frozenset())

As a result, the output is:
The vowels are:({'a', 'e', 'i', 'o', 'u'})
Empty frozen set is: frozenset()

Here, we take a variable that contains a tuple of letters and returns an immutable frozenset object.

Python frozenset() Parameters:

It takes only a single parameter.

iterable – It contains elements to initialize the frozenset with. The iterable can be a set, dictionary, tuple, etc.

Return value of frozenset() python function/method:

This function returns an immutable set initialized with elements of the iterable. In addition, it returns an empty frozenset if no parameters are passed.
For example,

vowels = ('a', 'e', 'i', 'o', 'u')
fs = frozenset(vowels)
print('The frozen set is:', fs)
print('The empty frozen set is:', frozenset())
fs.add('v')

As a result, the output is:
The frozen set is: frozenset({'a', 'o', 'u', 'i', 'e'})
The empty frozen set is: frozenset()
Traceback (most recent call last):
File ", line 5, in
fSet.add('v')
AttributeError: 'frozenset' object has no attribute 'add'

Python frozenset() for Dictionary:

While using a dictionary as an iterable for a frozen set, it takes the keys of the dictionary to make a set.
For example,

human = {"name": "Bruce", "age": 25, "gender": "male"}
fs = frozenset(human)
print('The frozen set is:', fs)

As a result, the output is:
The frozen set is: frozenset({'name', 'gender', 'age'})

Creating List & Tuple in Python Frozenset

We can create list and tuple from frozenset object using built-in functions.

For example,

fs = frozenset([1, 2, 3, 4, 5])
list_1 = list(fs)
print(list_1)
tuple_1 = tuple(fs)
print(tuple_1)

As a result, the output is:
[1, 2, 3, 4, 5] (1, 2, 3, 4, 5)

Operations of Python Frozenset

Frozenset can also perform different operations(like normal sets) like –

  • Copy
  • Difference
  • Intersection
  • Symmetric_difference
  • And union.

For example,

A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
# copying a frozenset
C = A.copy()
print(C)

# union
print(A.union(B))  
# intersection
print(A.intersection(B))  
# difference
print(A.difference(B))  
# symmetric_difference
print(A.symmetric_difference(B))

As a result, the output is:
frozenset({1, 2, 3, 4})
frozenset({1, 2, 3, 4, 5, 6})
frozenset({3, 4})
frozenset({1, 2})
frozenset({1, 2, 5, 6})

Different Types of Methods in Python Frozenset

There are different types of methods used in python frozenset. Some of the most common among these are:

Set add() Method :- It adds a given item to a set.
For example,

mySet = {'Mike', 'Bruce', 'Ben', 'Tom'}
mySet.add('Victor')
print(mySet)

As a result, the output is:
{'Mike', 'Bruce', 'Ben', 'Tom', 'Victor'}

Set clear() Method :- It erases or clears all the items from the set.
For example,

mySet = {'Mike', 'Bruce', 'Ben', 'Tom'}
mySet.clear()
print(mySet)

As a result, the output is:
set()

Set copy() Method :- It is used to create a copy of the set. It returns a shallow copy of that particular set.
For example,

set1 = {'Mike', 'Bruce', 'Ben', 'Tom'}
set2 = set1.copy()
print(set2)

As a result, the output is:
{'Mike', 'Bruce', 'Tom', 'Ben'}

Set difference() Method :- It returns the difference of two sets. If set A and B contains some kind of argument, the output contains a combination of items that are present in A but not in B.
For example,

A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7, 8}
C = A.difference(B)
print(C)

As a result, the output is:
{1, 2}

There are many more such methods that can be used in Python frozenset() like update(), union(), etc.

Use Cases For Frozenset

Above all, frozenset is a set that is immutable and it is best suited for use cases where-

We need to create a group of keys or some identifiers which we don’t want the user to change. So, we can store them in a frozenset and not allow anyone to change them.

For example, keys of a dictionary(mentioned above). If the keys play a functional role in the application, to get data from dictionary object. We can make the keys a frozenset.

You can also learn about Python List to String.

Like this article? Follow us on Facebook and LinkedIn.