Skip to content

Python frozenset: Overview and Examples

Python frozenset: Overview and Examples

In this tutorial, you’ll learn how to use the Python frozenset data structure. The frozenset in Python is often overlooked and many Python users don’t even know that it exists. The frozenset is a data structure that emulates the set, but is immutable.

By the end of this tutorial, you’ll have learned:

  • What a Python frozenset is and how it’s different from a regular set
  • How a Python frozenset can be used
  • What functions and methods are available for frozensets in Python

Overview of the Python frozenset Type

The Python frozenset data type is a set that is immutable. This means that each element in the set is unique and that the item itself cannot be changed (meaning it’s immutable). Because frozensets build on the Python set, they share many of the same characteristic. Let’s compare the two of them:

AttributePython frozensetPython set
Contains unique elementsYes, frozensets can only contain unique elementsYes, sets can only contain unique elements
IterableYes, items in a frozenset can be iterated overYes, items in a set can be iterated over
MutableNo, a frozenset cannot be mutatedYes, a set can be mutated
HashableYes, a frozenset is hashable and can be used as a key in a dictionaryNo, a set is not hashable and cannot be used as a key in a dictionary
A table comparing Python frozenset and set types

Now that you have a good overview of what frozenset data types are, let’s take a look at how to create them.

How to Create a frozenset in Python

In order to create a frozenset in Python, you can use the built-in frozenset() function. The function takes a single parameter, an iterable object (such as a list, tuple, set, etc.) and returns a frozenset. Similar to the set() constructor, the function will remove any duplicate items in the item passed in.

Let’s see how we can use the frozenset() function to create a frozenset:

# Creating a frozenset Object in Python
frozen = frozenset(['a', 'a', 'e', 'e', 'i', 'o', 'u'])
print(frozen)

# Returns: frozenset({'e', 'o', 'a', 'u', 'i'})

In the code block above, we passed a list into the frozenset() function. The list contained duplicate elements, which were removed when the frozenset was returned.

Checking for Membership in a Python frozenset

We can easily check for membership in a Python frozenset using the in operator. The in operator will return a boolean value, indicating whether an item exists in a frozenset or not.

To illustrate this with an example, let’s create a frozenset and check whether an item exists in it:

# Checking for Membership in a Python frozenset
frozen = frozenset(['a', 'a', 'e', 'e', 'i', 'o', 'u'])

item = 'a'
check = item in frozen

print(f'{item} exists in frozen: {check}')

# Returns:
# a exists in frozen: True

In the code block above, we check whether or not the string 'a' exists in our frozenset. Because the item does exist, the statement returns True.

Operations with Python frozensets

Python frozensets are immutable so you cannot use operations on them that modify the frozenset in any way. Doing this would raise an AttributeError and crash your program.

However, you are able to complete a number of different operations with frozensets. In particular, you can use the following methods on a frozenset:

  • .copy(), which copies a frozenset
  • .difference(), which returns the difference between two frozensets
  • .intersection(), which returns the intersection between two frozensets
  • .symmetric_difference(), which returns items in two frozensets except for their intersection
  • .union(), which returns the union between two sets

Copying a Frozenset in Python

Let’s take a look at how you can use these methods on frozensets. We can copy a frozenset by using the .copy() method:

# Copy a frozenset
frozen1 = frozenset([1, 2, 3, 4, 5])
frozen2 = frozenset([4, 5, 6, 7, 8])

frozen3 = frozen1.copy()
print(f'{frozen3=}')

# Returns:
# frozen3=frozenset({1, 2, 3, 4, 5})

Finding the Difference Between Frozensets in Python

We can use the .difference() method to check the difference between two frozensets, returning items that exist in the first frozenset but not in the second. In this case, the ordering matters.

# Check the difference between two frozensets
frozen1 = frozenset([1, 2, 3, 4, 5])
frozen2 = frozenset([4, 5, 6, 7, 8])

difference = frozen1.difference(frozen2)
print(f'{difference=}')

# Returns:
# difference=frozenset({1, 2, 3})

Finding the Intersection Between Two Frozensets in Python

We can use the .intersection() method to return items that exist in both frozensets. With this method, the ordering of the sets doesn’t matter:

# Check the intersection between two frozensets
frozen1 = frozenset([1, 2, 3, 4, 5])
frozen2 = frozenset([4, 5, 6, 7, 8])

intersection = frozen1.intersection(frozen2)
print(f'{intersection=}')

# Returns:
# intersection=frozenset({4, 5})

Finding the Symmetric Difference Between Two Frozensets in Python

We can use the .symmetric_difference() method to find items that exist in either frozenset, but not in both. In this case, the order of the frozensets doesn’t matter.

# Check the symmetric difference between two frozensets
frozen1 = frozenset([1, 2, 3, 4, 5])
frozen2 = frozenset([4, 5, 6, 7, 8])

symmetric_difference = frozen1.symmetric_difference(frozen2)
print(f'{symmetric_difference=}')

# Returns:
# symmetric_difference=frozenset({1, 2, 3, 6, 7, 8})

Finding the Union Between Two Frozensets in Python

We can use the .union() method to return the union of the two frozensets. If there are elements that exist in both frozensets, the duplicate values will be removed:

# Check the union between two frozensets
frozen1 = frozenset([1, 2, 3, 4, 5])
frozen2 = frozenset([4, 5, 6, 7, 8])

union = frozen1.union(frozen2)
print(f'{union=}')

# Returns:
# union=frozenset({1, 2, 3, 4, 5, 6, 7, 8})

In the following section, you’ll learn how to use Python frozensets in a dictionary.

Using a Python frozenset in a Python Dictionary

Because frozensets in Python are immutable, they can be used as keys in Python dictionaries. A requirement of a key is that the item is hashable and immutable. As you learned in our earlier comparison of sets and frozensets, this is true for frozensets but not for normal sets.

Let’s see how we can use a frozenset as a key in a Python dictionary:

# Using a frozenset in a Python Dictionary
dictionary = {
    frozenset([1,2,3]): 'a'
}

print(dictionary)

# Returns:
# {frozenset({1, 2, 3}): 'a'}

Conclusion

In this tutorial, you learned about the frozenset data type in Python. You first learned what the frozenset is and how it is different from a normal set. Then, you learned how to create a frozenset, using the built-in frozenset() function.

You then learned how to use frozensets to check for membership, as well as the different methods that are available to frozensets in Python. Finally, you learned how to use a Python frozenset as a key to a dictionary.

Additional Resources

To learn more about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Leave a Reply

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