Set and FrozenSet in Python: What’s the difference?

Updated: February 12, 2024 By: Guest Contributor Post a comment

Overview

In Python, sets are a collection data type that are mutable, unordered, and do not allow duplicate elements. This makes them highly useful for doing mathematical set operations like unions, intersections, and set difference. Frozen sets, on the other hand, are just like sets but immutable. If you’ve been confused about when to use a set versus a frozen set in Python, this tutorial will walk you through the differences, use-cases, and provide you with code examples from basic to advanced levels to solidify your understanding.

Understanding Sets

To start with, let’s look at how to create a set. You can create a set by using curly braces {}, or the built-in set() function. Elements in a set are unique and unordered:

# Creating a set
my_set = {1, 2, 3, 4, 5}
print(my_set)

# Using set() function to create a set from a list
my_list = [1, 2, 2, 3, 4]
my_set_from_list = set(my_list)
print(my_set_from_list)

Note that when printing my_set_from_list, it only displays unique elements.

Set Operations

Sets in Python are powerful because of their ability to perform mathematical set operations. Here’s how you can do some of the basic operations:

# Union
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set)

# Intersection
intersection_set = set1.intersection(set2)
print(intersection_set)

# Difference
difference_set = set1 - set2
print(difference_set)

The output demonstrates how easy it is to combine sets, find common elements, or determine differences between them.

Understanding FrozenSets

Now let’s shift our focus to frozen sets. As mentioned earlier, frozen sets are immutable versions of sets. They support the same operations as sets, but you cannot add or remove elements after creation. Here’s how you can create a frozen set:

# Creating a frozenset
frozen = frozenset([1, 2, 3, 4, 5])
print(frozen)

Observe that we use the frozenset() function, and similar to sets, duplicated elements are not allowed.

Comparing Sets and FrozenSets

While both sets and frozensets are useful for storing unique elements and performing set operations, the key difference is mutability. Sets are mutable, which means you can change their content. Frozen sets, however, are fixed and cannot be changed after they are created. This immutability makes frozensets hashable, allowing them to be used as keys in dictionaries or elements of other sets, which is not possible with regular sets.

# Using frozenset as dictionary key
my_dict = {frozenset([1, 2, 3]): "hello"}
print(my_dict)

# Attempting to use a regular set as dictionary key will throw an error
try:
    my_dict = {{1, 2, 3}: "world"}
except TypeError as e:
    print(f"Error: {e}")

Advanced Set Operations

Moving beyond basic set operations, Python also offers several advanced set methods. These include methods like add(), remove(), and discard() for sets, and similarly, you can perform non-mutating operations on frozensets.

# Adding an element to a set
my_set.add(6)
print(my_set)

# Removing an element safely with discard
my_set.discard(5)
print(my_set)

# Attempting to remove an element not in the set with remove method
try:
    my_set.remove(10)
except KeyError as e:
    print(f"Error: {e}")

As these examples show, attempting to modify a frozenset in a similar manner will result in an AttributeError because frozensets do not support methods that alter the set.

Use Cases for Sets and FrozenSets

Understanding when to use sets or frozensets depends on your data’s mutability requirement. Use sets when you need a unique collection of items that will change over time. Frozen sets are better suited for situations where you need the qualities of a set but with immutable data, such as keys in a dictionary or when performing set operations on sets themselves.

Conclusion

In summary, sets and frozensets in Python serve similar purposes but differ significantly in their mutability. Sets are mutable and great for collections of unique elements that may change. Frozen sets, being immutable, are useful when you need fixed sets that can participate as dictionary keys or set elements. Understanding these differences is crucial for effectively harnessing the power of sets in Python programming.