Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python frozenset() Function

Python frozenset() Function

Python3 Built-in Functions Python3 built-in function


frozenset() is a built-in Python function that creates an immutable set (frozenset).

The difference between frozenset and set is that frozenset is immutable: after creation, elements cannot be added, removed, or modified. Because of this immutability, frozenset can be used as a dictionary key or an element of a set.

Word meaning: frozenset is short for "frozen set", meaning an immutable set.


Basic syntax and parameters

Syntax format


frozenset(iterable)

Parameter Description

- Type: iterable - Description: the iterable to convert to an immutable set.

Function description


Example

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 only)

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 removes duplicates automatically.
  2. It can be used with all kinds of iterables.
  3. frozenset is immutable and has no add, remove, or similar methods.

Example 2: uses of frozenset

Example

frozenset can be used as a dictionary key

d

=

{

frozenset

(

[

1

,

2

]

)

:

"A"

,

frozenset

(

[

3

,

4

]

)

:

"B"

}

print

(

d

)

 

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

frozenset can be an element 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 a dictionary key or an element of a set.


Python3 Built-in Functions Python3 built-in function