Frozenset Definition (Immutable Sets)

🏷️ Tuples and Sets / Frozen Sets

When working with sets in Python, you may encounter situations where you need a collection of unique items that cannot be changed after creation. This is where frozensets come in. A frozenset is essentially an immutable version of a regular setβ€”once created, you cannot add, remove, or modify its elements. This makes frozensets ideal for use as dictionary keys or as elements within other sets, since they are hashable and unchangeable.


βš™οΈ What is a Frozenset?

  • A frozenset is a built-in Python data type that represents an immutable collection of unique elements.
  • Unlike a regular set (created with curly braces {} or the set() constructor), a frozenset cannot be modified after creation.
  • Frozensets are hashable, meaning they can be used as keys in dictionaries or as elements inside other sets.
  • They are created using the frozenset() constructor, which accepts any iterable (like a list, tuple, or string).

Example: Creating a frozenset from a list of numbers: frozenset([1, 2, 3, 4]) results in a frozenset containing 1, 2, 3, 4.


πŸ› οΈ Key Characteristics of Frozensets

  • Immutable: Once created, you cannot add, remove, or change any elements. Methods like add(), remove(), or discard() are not available.
  • Unordered: Like regular sets, frozensets do not maintain any specific order for their elements.
  • Unique Elements: Duplicate values are automatically removed during creation.
  • Hashable: Because frozensets are immutable, they can be used in contexts where hashability is required, such as dictionary keys.
  • Supports Set Operations: Frozensets support all standard set operations like union, intersection, difference, and symmetric difference.

πŸ“Š Frozenset vs Regular Set – Quick Comparison

Feature Regular Set Frozenset
Mutability Mutable (can add/remove elements) Immutable (cannot change after creation)
Hashable No (cannot be used as dictionary key) Yes (can be used as dictionary key)
Creation Syntax {1, 2, 3} or set([1, 2, 3]) frozenset([1, 2, 3])
Methods Available add(), remove(), discard(), pop(), clear() Only non-modifying methods like union(), intersection(), difference()
Use Case When you need a changing collection of unique items When you need a fixed, hashable collection of unique items

πŸ•΅οΈ Common Operations with Frozensets

  • Creating a frozenset: Use the frozenset() constructor with any iterable. For example: frozenset('hello') produces frozenset({'h', 'e', 'l', 'o'}) (note the duplicate l is removed).
  • Checking membership: Use the in keyword. For example: 3 in frozenset([1, 2, 3]) returns True.
  • Set operations: Frozensets support union (|), intersection (&), difference (-), and symmetric difference (^). For example: frozenset([1, 2]) | frozenset([2, 3]) returns frozenset({1, 2, 3}).
  • Length: Use the len() function. For example: len(frozenset([10, 20, 30])) returns 3.
  • Iteration: You can loop through a frozenset using a for loop, just like any iterable.

πŸ§ͺ Practical Use Cases for Engineers

  • Dictionary Keys: Since frozensets are hashable, you can use them as keys in dictionaries. This is useful when you need to group data by a fixed set of attributes.
  • Caching or Memoization: Use a frozenset as a key to cache results of expensive operations that depend on a fixed set of inputs.
  • Configuration Sets: Store immutable configuration options or allowed values that should never change during program execution.
  • Set of Sets: Because a regular set cannot contain another set (since sets are unhashable), you can use frozensets to create a set of sets. For example: {frozenset([1, 2]), frozenset([3, 4])} is valid.
  • Data Integrity: When you want to ensure that a collection of unique items remains constant throughout your program, frozensets provide a safety guarantee against accidental modifications.

βœ… Summary

  • A frozenset is an immutable, unordered collection of unique elements.
  • It is created using the frozenset() constructor and cannot be modified after creation.
  • Frozensets are hashable, making them suitable for use as dictionary keys or elements within other sets.
  • They support all standard set operations like union, intersection, and difference.
  • Use frozensets when you need a fixed, unchangeable collection of unique items that must remain constant throughout your code.

By understanding frozensets, you add a powerful tool to your Python toolkitβ€”one that ensures data integrity and enables advanced data structures like sets of sets and hashable dictionary keys.


A frozenset is an immutable version of a set that cannot be modified after creation, making it hashable and usable as a dictionary key or set element.

πŸ”§ Example 1: Creating a frozenset from a list

This example shows how to create a frozenset from a list of numbers.

numbers = [1, 2, 3, 4, 5]
frozen_numbers = frozenset(numbers)
print(frozen_numbers)

πŸ“€ Output: frozenset({1, 2, 3, 4, 5})


πŸ”§ Example 2: Frozenset removes duplicates automatically

This example demonstrates that frozenset, like set, removes duplicate values.

values = [1, 2, 2, 3, 3, 3, 4]
frozen_values = frozenset(values)
print(frozen_values)

πŸ“€ Output: frozenset({1, 2, 3, 4})


πŸ”§ Example 3: Frozenset cannot be modified after creation

This example shows that frozenset does not support add, remove, or discard operations.

frozen = frozenset([10, 20, 30])
try:
    frozen.add(40)
except AttributeError as error:
    print("Error:", error)

πŸ“€ Output: Error: 'frozenset' object has no attribute 'add'


πŸ”§ Example 4: Using frozenset as a dictionary key

This example demonstrates that frozenset can be used as a dictionary key because it is hashable.

group_a = frozenset(["Alice", "Bob", "Charlie"])
group_b = frozenset(["Dave", "Eve", "Frank"])

teams = {
    group_a: "Team Alpha",
    group_b: "Team Beta"
}

print(teams[group_a])

πŸ“€ Output: Team Alpha


πŸ”§ Example 5: Frozenset inside another set

This example shows that frozenset can be an element of a regular set, unlike a mutable set.

set_a = frozenset([1, 2, 3])
set_b = frozenset([4, 5, 6])
set_c = frozenset([7, 8, 9])

collection = {set_a, set_b, set_c}
print(collection)

πŸ“€ Output: {frozenset({1, 2, 3}), frozenset({4, 5, 6}), frozenset({7, 8, 9})}


Comparison: set vs frozenset

Feature set frozenset
Mutable (can add/remove) βœ… Yes ❌ No
Hashable (can be dictionary key) ❌ No βœ… Yes
Can be element of another set ❌ No βœ… Yes
Created with set() or {} frozenset()

When working with sets in Python, you may encounter situations where you need a collection of unique items that cannot be changed after creation. This is where frozensets come in. A frozenset is essentially an immutable version of a regular setβ€”once created, you cannot add, remove, or modify its elements. This makes frozensets ideal for use as dictionary keys or as elements within other sets, since they are hashable and unchangeable.


βš™οΈ What is a Frozenset?

  • A frozenset is a built-in Python data type that represents an immutable collection of unique elements.
  • Unlike a regular set (created with curly braces {} or the set() constructor), a frozenset cannot be modified after creation.
  • Frozensets are hashable, meaning they can be used as keys in dictionaries or as elements inside other sets.
  • They are created using the frozenset() constructor, which accepts any iterable (like a list, tuple, or string).

Example: Creating a frozenset from a list of numbers: frozenset([1, 2, 3, 4]) results in a frozenset containing 1, 2, 3, 4.


πŸ› οΈ Key Characteristics of Frozensets

  • Immutable: Once created, you cannot add, remove, or change any elements. Methods like add(), remove(), or discard() are not available.
  • Unordered: Like regular sets, frozensets do not maintain any specific order for their elements.
  • Unique Elements: Duplicate values are automatically removed during creation.
  • Hashable: Because frozensets are immutable, they can be used in contexts where hashability is required, such as dictionary keys.
  • Supports Set Operations: Frozensets support all standard set operations like union, intersection, difference, and symmetric difference.

πŸ“Š Frozenset vs Regular Set – Quick Comparison

Feature Regular Set Frozenset
Mutability Mutable (can add/remove elements) Immutable (cannot change after creation)
Hashable No (cannot be used as dictionary key) Yes (can be used as dictionary key)
Creation Syntax {1, 2, 3} or set([1, 2, 3]) frozenset([1, 2, 3])
Methods Available add(), remove(), discard(), pop(), clear() Only non-modifying methods like union(), intersection(), difference()
Use Case When you need a changing collection of unique items When you need a fixed, hashable collection of unique items

πŸ•΅οΈ Common Operations with Frozensets

  • Creating a frozenset: Use the frozenset() constructor with any iterable. For example: frozenset('hello') produces frozenset({'h', 'e', 'l', 'o'}) (note the duplicate l is removed).
  • Checking membership: Use the in keyword. For example: 3 in frozenset([1, 2, 3]) returns True.
  • Set operations: Frozensets support union (|), intersection (&), difference (-), and symmetric difference (^). For example: frozenset([1, 2]) | frozenset([2, 3]) returns frozenset({1, 2, 3}).
  • Length: Use the len() function. For example: len(frozenset([10, 20, 30])) returns 3.
  • Iteration: You can loop through a frozenset using a for loop, just like any iterable.

πŸ§ͺ Practical Use Cases for Engineers

  • Dictionary Keys: Since frozensets are hashable, you can use them as keys in dictionaries. This is useful when you need to group data by a fixed set of attributes.
  • Caching or Memoization: Use a frozenset as a key to cache results of expensive operations that depend on a fixed set of inputs.
  • Configuration Sets: Store immutable configuration options or allowed values that should never change during program execution.
  • Set of Sets: Because a regular set cannot contain another set (since sets are unhashable), you can use frozensets to create a set of sets. For example: {frozenset([1, 2]), frozenset([3, 4])} is valid.
  • Data Integrity: When you want to ensure that a collection of unique items remains constant throughout your program, frozensets provide a safety guarantee against accidental modifications.

βœ… Summary

  • A frozenset is an immutable, unordered collection of unique elements.
  • It is created using the frozenset() constructor and cannot be modified after creation.
  • Frozensets are hashable, making them suitable for use as dictionary keys or elements within other sets.
  • They support all standard set operations like union, intersection, and difference.
  • Use frozensets when you need a fixed, unchangeable collection of unique items that must remain constant throughout your code.

By understanding frozensets, you add a powerful tool to your Python toolkitβ€”one that ensures data integrity and enables advanced data structures like sets of sets and hashable dictionary keys.

Interactive Views

You are currently in πŸ“š All-in-One mode. Use the tabs at the top to switch to πŸ“– Theory Only or πŸ’» Code Only views.

A frozenset is an immutable version of a set that cannot be modified after creation, making it hashable and usable as a dictionary key or set element.

πŸ”§ Example 1: Creating a frozenset from a list

This example shows how to create a frozenset from a list of numbers.

numbers = [1, 2, 3, 4, 5]
frozen_numbers = frozenset(numbers)
print(frozen_numbers)

πŸ“€ Output: frozenset({1, 2, 3, 4, 5})


πŸ”§ Example 2: Frozenset removes duplicates automatically

This example demonstrates that frozenset, like set, removes duplicate values.

values = [1, 2, 2, 3, 3, 3, 4]
frozen_values = frozenset(values)
print(frozen_values)

πŸ“€ Output: frozenset({1, 2, 3, 4})


πŸ”§ Example 3: Frozenset cannot be modified after creation

This example shows that frozenset does not support add, remove, or discard operations.

frozen = frozenset([10, 20, 30])
try:
    frozen.add(40)
except AttributeError as error:
    print("Error:", error)

πŸ“€ Output: Error: 'frozenset' object has no attribute 'add'


πŸ”§ Example 4: Using frozenset as a dictionary key

This example demonstrates that frozenset can be used as a dictionary key because it is hashable.

group_a = frozenset(["Alice", "Bob", "Charlie"])
group_b = frozenset(["Dave", "Eve", "Frank"])

teams = {
    group_a: "Team Alpha",
    group_b: "Team Beta"
}

print(teams[group_a])

πŸ“€ Output: Team Alpha


πŸ”§ Example 5: Frozenset inside another set

This example shows that frozenset can be an element of a regular set, unlike a mutable set.

set_a = frozenset([1, 2, 3])
set_b = frozenset([4, 5, 6])
set_c = frozenset([7, 8, 9])

collection = {set_a, set_b, set_c}
print(collection)

πŸ“€ Output: {frozenset({1, 2, 3}), frozenset({4, 5, 6}), frozenset({7, 8, 9})}


Comparison: set vs frozenset

Feature set frozenset
Mutable (can add/remove) βœ… Yes ❌ No
Hashable (can be dictionary key) ❌ No βœ… Yes
Can be element of another set ❌ No βœ… Yes
Created with set() or {} frozenset()