Python frozenset() — A Simple Guide with Video

Python’s built-in frozenset() function creates and returns a new frozenset object. A frozenset is an immutable set—so you cannot change the frozenset after creation and set methods such as add() or remove() don’t work on the frozenset. Without an argument, frozenset() returns an empty frozenset. With the optional argument, frozenset(iter) initializes the new frozenset with the elements in the iterable.

Read more about sets in our full tutorial about Python Sets.

frozenset() function Python

Usage

Learn by example! Here are some examples of how to use the frozenset() built-in function:

You can create an empty set by skipping the argument:

>>> frozenset()
frozenset()

If you pass an iterable—such as a list, tuple, set, or dictionary—you obtain a new frozenset object with elements obtained from the iterable:

>>> frozenset([1, 2, 3])
frozenset({1, 2, 3})

Note that it really creates a new frozenset object that is different from the one passed as an argument:

>>> set_a = {1, 2, 3}
>>> frozenset_a = frozenset(set_a)
>>> set_a == frozenset_a
True
>>> set_a is frozenset_a
False

The new set frozenset_a has the same elements as the original set set_a. But it’s still a different object as you can see from the check set_a is frozenset_a that returns False.

You cannot add or remove elements from a frozenset because it’s immutable:

>>> s = frozenset({'Alice', 'Bob', 'Ann'})
>>> s.add('Ben')
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    s.add('Ben')
AttributeError: 'frozenset' object has no attribute 'add'
>>> s.remove('Alice')
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    s.remove('Alice')
AttributeError: 'frozenset' object has no attribute 'remove'

This would work for Python sets that are mutable:

>>> s = {'Alice', 'Bob', 'Ann'}
>>> s.add('Ben')
>>> s.remove('Alice')
>>> s
{'Bob', 'Ann', 'Ben'}

Conceptually, the only difference between sets and frozensets is that the former are mutable and the latter are immutable. Consequently, the latter doesn’t provide the same methods to modify an existing set.

Video frozenset()

Syntax frozenset()

You can use the frozenset() method with or without the optional iterable argument.

Syntax: There are two ways of using the constructor:
frozenset() -> new empty frozenset
frozenset(iterable) -> new frozenset initialized with elements in iterable


Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners


Frozenset Operations

Here are a few examples that show which operations you can perform on a frozenset:

# Frozenset Operations

# initialize frozensets A and B
A = frozenset(['Alice', 'Bob', 'Carl'])
B = frozenset(['Bob', 'Carl', 'David'])

# copy
C = A.copy()
print(C)
# frozenset({'Alice', 'Bob', 'Carl'})

# union
print(A.union(B))
# frozenset({'Alice', 'David', 'Bob', 'Carl'})

# intersection
print(A.intersection(B))
# frozenset({'Bob', 'Carl'})

# difference
print(A.difference(B))
# frozenset({'Alice'})

# symmetric difference
print(A.symmetric_difference(B))
# frozenset({'Alice', 'David'})

# isdisjoint()
print(A.isdisjoint(C))
# False

# issubset()
C = A.union(B)
print(C.issubset(B))
# False

# issuperset()
print(C.issuperset(B))
# True

As a rule of thumb: you can perform all set operations but you cannot modify an existing set.

Summary

Python’s built-in frozenset() function creates and returns a new frozenset object that is an immutable version of a Python set.

  • When used without an argument, it returns an empty frozenset. As you cannot change a frozenset object, this wouldn’t make a lot of sense.
  • When used with the optional iterable argument, it initializes the new frozenset with the elements in the iterable.
>>> frozenset()
frozenset()
>>> frozenset([1, 2, 3])
frozenset({1, 2, 3})

References: https://docs.python.org/3/library/stdtypes.html#frozenset

I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:


Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!