Python Frozensets
 

Python Frozensets

 

Python frozensets are same as the set data type in Python the only difference is that frozensets are immutable which means you can’t add or remove the elements once it is created.

Frozensets are hashable and can be used as keys to a dictionary. In this article, you will learn python frozensets with some examples.

How to create a frozenset in Python

The frozensets() function is used to create frozensets in Python. Syntax of this function is given below –

frozenset(iterable_object_name)

Frozenset function takes the iterable object as an input parameter and returns an equivalent frozenset object.

For example –

x= frozenset([1,9,6,7,0,3])
y= frozenset([5,1,9,4,7,2])
# Now check the type of x and y
print(type(x))
print(type(y))

You can see the output in the given image –

Now if you try to add or remove elements from these frozensets it will through an error.

Set operations on frozensets

The Python frozenset supports various methods which includes union(), intersection(), difference(), symmetric_difference(), issubset(), isdisjoint(), etc.

You can perform various set operations on frozenset in Python.

For example –

print(f"Union of x and y is {x.union(y)}")
print(f"Intersection of x and y is {x.intersection(y)}")
print(f"x difference y is {x.difference(y)}")
print(f"Symmetric difference of x and y is {x.symmetric_difference(y)}")
print(f"Is x is subset of y {x.issubset(y)}")
print(f"x and y are disjoint set {x.isdisjoint(y)}")

You can see the output in the given image –

Conclusion

Now you can try other set operations on Python frozensets. If you have a query then leave it in the comments below.

Previous Python Sets
Next Python List vs Array
 

About author

You might also like

Python Programming 0 Comments

Program in Python to print Fibonacci sequence

A Fibonacci sequence is consists of integer numbers whose first and second term is 0 and 1 respectively you can determine the coming terms by adding the previous two numbers

Programming 0 Comments

Python if else and nested if else statements

In programming conditional statements provides a way in which the computer takes a decision based on whether a condition is true or false. The if and else statements are common

Python Programming 0 Comments

Python List Comprehension

A python list can hold multiple different types of values in a single variable. In our previous article on Python list data type, we had discussed the Python lists, how

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Reply