Python frozenset() Function

Python3 内置函数Python3 Built-in Functions


frozenset()is a built-in function in Python used to create an immutable set (frozenset).

The difference between frozenset and set is that frozenset is immutable; after creation, elements cannot be added, removed, or modified. Due to its immutability, frozenset can be used as dictionary keys or elements of a set.

Word Definition: frozensetis the abbreviation for "frozen set," representing an immutable set.


Basic Syntax and Parameters

Syntax Format

frozenset(iterable)

Parameter Description

  • Parameter iterable:
    • Type: iterable object
    • Description: The iterable object to convert to an immutable set.

Function Description

  • Return value: Returns a frozenset object.
  • Special value: Returns an empty frozenset when called without arguments.

Examples

Example 1: Creating a frozenset

Example

# Create from a list
lst = [1, 2, 3, 2, 1]
fs = frozenset(lst)
print(fs)        # Output: frozenset({1, 2, 3})

# Create from a string
s = "hello"
fs = frozenset(s)
print(fs)        # Output: frozenset({'h', 'e', 'l', 'o'})

# Create from a dictionary (keys)
d = {"a": 1, "b": 2}
fs = frozenset(d)
print(fs)        # Output: frozenset({'a', 'b'})

# Empty frozenset
fs = frozenset()
print(fs)        # Output: frozenset()

Expected output:

frozenset({1, 2, 3})
frozenset({'h', 'e', 'l', 'o'})
frozenset({'a', 'b'})
frozenset()

Code analysis:

  1. frozenset automatically removes duplicates.
  2. It can be used with various iterable objects.
  3. frozenset is immutable and does not have methods like add or remove.

Example 2: Uses of frozenset

Example

# frozenset can be used as dictionary keys
d = {frozenset([1, 2]): "A", frozenset([3, 4]): "B"}
print(d)  # Output: {frozenset({1, 2}): 'A', frozenset({3, 4}): 'B'}

# frozenset can be elements of a set
s = {frozenset([1, 2]), frozenset([3, 4])}
print(s)  # Output: {frozenset({1, 2}), frozenset({3, 4})}

# frozenset supports set operations (but does not modify the original set)
fs1 = frozenset([1, 2, 3])
fs2 = frozenset([2, 3, 4])
print(fs1 & fs2)  # Output: frozenset({2, 3}) intersection
print(fs1 | fs2)  # Output: frozenset({1, 2, 3, 4}) union

Expected output:

{frozenset({1, 2}): 'A', frozenset({3, 4}): 'B'}
{frozenset({1, 2}), frozenset({3, 4})}
frozenset({2, 3})
frozenset({1, 2, 3, 4})

The main use of frozenset is as dictionary keys or elements of a set.


Python3 内置函数Python3 Built-in Functions


Other Extensions