[ Web Proxy ]
URL:
Viewing: https://www.tutorialspoint.com/python/python-frozenset-function.htm [Back]  [Original]

Python frozenset() Function
Tutorials Courses Jobs Login
Selected Reading
Home Python Python frozenset() Function

Python frozenset() Function



The Python frozenset() function is used to create an immutable frozenset object.

In Python, a frozenset is similar to a set, but with a key difference it is an immutable (unchangeable) collection of unique elements. Once a frozenset is created, you cannot add, remove, or modify its elements. Like sets, frozensets are defined using curly braces {}, but with the "frozenset()" function.

Syntax

Following is the syntax of Python frozenset() function

frozenset([iterable])

Parameters

This function accepts an optional parameter representing the iterable object like a list, tuple, set, or another iterable.

Return Value

This function returns a new frozenset object containing elements from the given iterable.

Example 1

In the following example, we are using the frozenset() function to convert the list "my_list" into a frozenset by removing duplicate elements

my_list = [1, 2, 3, 3, 4]
frozen_set = frozenset(my_list)
print('The frozenset object obtained is:',frozen_set)

Output

Following is the output of the above code

The frozenset object obtained is: frozenset({1, 2, 3, 4})

Example 2

Here, we are using the frozenset() function to directly convert the set "my_set" into a frozenset

my_set = {4, 5, 6}
frozen_set = frozenset(my_set)
print('The frozenset object obtained is:',frozen_set)

Output

Output of the above code is as follows

The frozenset object obtained is: frozenset({4, 5, 6})

Example 3

In here, we are using the frozenset() function to convert the string "hello" into a frozenset of its unique characters

my_string = "hello"
frozen_set = frozenset(my_string)
print('The frozenset object obtained is:',frozen_set)

Output

The result obtained is as shown below

The frozenset object obtained is: frozenset({'h', 'e', 'o', 'l'})

Example 4

In this case, we use the frozenset() function without any arguments to create an empty frozenset "(frozenset())". This can be useful as an immutable placeholder

empty_frozen_set = frozenset()
print('The frozenset object obtained is:',empty_frozen_set)

Output

Following is the output of the above code

The frozenset object obtained is: frozenset()

Example 5

In this example, we use the frozenset() function to process the tuple "my_tuple", removing duplicate elements. The resulting frozenset is immutable

my_tuple = (1, 2, 3, 3)
frozen_set = frozenset(my_tuple)
print('The frozenset object obtained is:',frozen_set)

Output

The result produced is as follows

The frozenset object obtained is: frozenset({1, 2, 3})
python_type_casting.htm
Tutorix - AI Tutor [Tutorix - AI Tutor]
Print Page
Advertisements

Web Proxy Viewer  |  New URL  |  Original Page