Python frozenset - Convert a list, set, tuple, dictionary to a frozenset

The frozenset built-in function converts an iterable object to a frozenset.

a = [5, 6, 7]

f = frozenset(a)

print(f)  # frozenset({5, 6, 7})
print(type(f))  # <class 'frozenset'>

A frozenset object is an immutable iterable. You can't update a frozenset.

a = [5, 6, 7]
a.append(8)

f = frozenset(a)
f.append(8)
# AttributeError: 'frozenset' object has no attribute 'append'

You can iterate a frozenset.

a = [5, 6, 7]
a.append(8)

f = frozenset(a)

for i in f:
    print(i)

# 8
# 5
# 6
# 7

How to use frozenset function

a = frozenset(1, 2, 3)
# TypeError: frozenset expected at most 1 argument, got 3

b = frozenset(1)
# TypeError: 'int' object is not iterable

c = frozenset('Apple')
print(c)  # frozenset({'e', 'p', 'l', 'A'})

A frozenset object has only distinct values as set.

a = [5, 6, 7, 7]

f = frozenset(a)

print(f)  # frozenset({5, 6, 7})

List, set, tuple and dictionary to frozenset

a1 = [1, 2, 3]
f1 = frozenset(a1)
print(f1)  # frozenset({1, 2, 3})

a2 = {1, 2, 3}
f2 = frozenset(a2)
print(f2)  # frozenset({1, 2, 3})

a3 = (1, 2, 3)
f3 = frozenset(a3)
print(f3)  # frozenset({1, 2, 3})

a4 = {'Apple': 114, 'Microsoft': 209}
f4 = frozenset(a4)
print(f4)  # frozenset({'Microsoft', 'Apple'})

Python Set

Python Tutorial