Level 1
0 / 100 XP

Frozensets

In this lesson, we will be discussing the frozenset data type, which is used to represent an immutable collection of unique items.

A frozenset is similar to a set, but it is immutable, which means that its items cannot be changed once it has been created. This makes frozensets useful in situations where you need a set-like data type, but you don't want the items to be mutable. In Python, frozensets are represented using the frozenset data type.

Here's an example of how to create a frozenset:

Python
# Create a frozenset of numbers numbers = frozenset({1, 2, 3, 4, 5}) # Print the frozenset print(numbers)

In this example, we create a frozenset of numbers and then print the frozenset to the console. As you can see, the frozenset contains the same items as the original set, but it is immutable, which means that we cannot add or remove items from it.

Frozenset Operations

Frozensets also support set operations, such as union, intersection, and difference. Here's an example of how to perform set operations on frozensets:

Python
# Create two frozensets of numbers set1 = frozenset({1, 2, 3, 4, 5}) set2 = frozenset({4, 5, 6, 7, 8}) # Perform set operations on the frozensets union = set1.union(set2) intersection = set1.intersection(set2) difference = set1.difference(set2) # Print the results print(f"Union: {union}") print(f"Intersection: {intersection}") print(f"Difference: {difference}")

In this example, we create two frozensets of numbers and then perform several set operations on them. We use the union() method to compute the union of the two sets, the intersection() method to compute the intersection of the two sets, and the difference() method to compute the difference between the two sets. Finally, we print the results to the console.

Sounding familiar? Tuples vs Frozensets

Now you might be wondering... isn't literally the sa…