English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Frozenset() Usage and Example

Python built-in functions

The Frozenset() method returns an immutable frozenset object initialized by the elements of the given iterable.

The frozen set is justPython setan immutable version of the object. Although the elements of the set can be modified at any time, the elements of the frozen set remain unchanged after creation.

Therefore, the frozen set can be used asin the DictionaryAn element or used as an element of another set. However, like a set, it is also not ordered (elements can be set at any index).

The syntax of the Frozenset() method is:

frozenset([iterable])

Frozenset() parameters

The Frozenset() method can optionally use a single parameter:

  • iterable (optional) -iterable, it contains elements for initializing Frozenset.
    Can set Iterable, Dictionary,Tupleetc.

Frozenset() return value

The Frozenset() method returns an immutable Frozenset (frozen set) initialized with the elements of the given iterable.

If no parameters are passed, it returns an empty Frozenset.

Example1How does frozenset() work in Python?

# Tuple vowels
vowels = ('a', 'e', 'i', 'o', 'u')
fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())

When running the program, the output is:

The frozen set is: frozenset({'o', 'i', 'e', 'u', 'a'})
The empty frozen set is: frozenset()

Example2Dictionary's frozenset()

When you use a dictionary as an iterable object for frozenset. You only need the keys of the dictionary to create the set.

# Random dictionary
person = {'name': 'John', 'age': 23, 'sex': 'male'}
fSet = frozenset(person)
print('The frozen set is:', fSet)

When running the program, the output is:

The frozen set is: frozenset({'name', 'sex', 'age'})

Frozenset operations

Like a regular set, frozenset can also perform different operations, such as union, intersection, etc.

Python built-in functions