search

What is the difference between "set" and "frozenset" in Python?

In Python, set and frozenset are both used to represent unordered collections of unique elements, but they have some key differences:

Mutability:

  • set: Sets are mutable, meaning that you can add, remove, or modify elements in a set after it is created. You can use methods like add(), remove(), and discard() to modify a set.
  • frozenset: Frozensets are immutable, meaning that once created, you cannot modify the elements of a frozenset. Frozensets do not have methods to add or remove elements.

Hashability:

  • set: Sets are not hashable, which means that you cannot use a set as an element of another set. This is because sets are mutable, and mutable objects cannot be used as elements in sets or as keys in dictionaries.
  • frozenset: Frozensets are hashable, so you can use a frozenset as an element of another set or as a key in a dictionary. Frozensets are considered immutable, and thus they can be safely used as elements or keys.

Usage:

  • set: Sets are commonly used when you need to store a collection of unique elements and perform operations like set union, intersection, and difference. Sets are useful when you need to add or remove elements dynamically.
  • frozenset: Frozensets are useful when you need an immutable and hashable version of a set. They are often used as keys in dictionaries or as elements in other sets when immutability and hashability are required.

Here's an example to illustrate the difference between set and frozenset:

# Example with set
my_set = set([1, 2, 3])
my_set.add(4)
my_set.remove(2)
print(my_set)  # Output: {1, 3, 4}

# Example with frozenset
my_frozenset = frozenset([1, 2, 3])
print(my_frozenset)  # Output: frozenset({1, 2, 3})

In this example, a set my_set is created initially with elements 1, 2, and 3. The add() method is used to add the element 4 to the set, and the remove() method is used to remove the element 2. The resulting set is 4.

On the other hand, a frozenset my_frozenset is created initially with elements 1, 2, and 3. Since frozensets are immutable, there are no methods to add or remove elements. The resulting frozenset is frozenset(3).

To summarize, sets are mutable and can be modified after creation, while frozensets are immutable and cannot be modified once created. Sets are not hashable, while frozensets are hashable and can be used as keys or elements in other sets. Choose between set and frozenset based on whether you need mutability and hashability for your specific use case.

Related Questions You Might Be Interested