Sobes.tech
Junior — Middle

What is the difference between mutable and immutable sets in Python?

sobes.tech AI

Answer from AI

In Python, there are mutable and immutable sets:

  • set — a mutable set. You can add or remove elements after creation.
  • frozenset — an immutable set. Its contents cannot be changed after creation.

Differences:

  • Mutable set supports methods like add(), remove(), discard(), etc.
  • frozenset does not support modification but can be used as a key in dictionaries or as an element of other sets because it is hashable.

Example:

s = set([1, 2, 3])
s.add(4)  # works

fs = frozenset([1, 2, 3])
# fs.add(4)  # will raise AttributeError

# frozenset can be used as a dictionary key
my_dict = {fs: "immutable set"}