w3resource

Python: Frozensets

Python sets: Exercise-13 with Solution

Write a Python program that uses frozensets.

Note: Frozensets behave just like sets except they are immutable.

Visual Presentation:

Python Sets: Frozensets.

Sample Solution:

Python Code:

# Create a frozenset 'x' with elements [1, 2, 3, 4, 5].
x = frozenset([1, 2, 3, 4, 5])

# Create a frozenset 'y' with elements [3, 4, 5, 6, 7].
y = frozenset([3, 4, 5, 6, 7])

# Use the 'isdisjoint()' method to check if 'x' and 'y' have no common elements and print the result.
# Return True if the sets have no elements in common with each other.
print(x.isdisjoint(y))

# Use the 'difference()' method to find the elements in 'x' that are not in 'y' and print the result.
# Return a new frozenset with elements in 'x' that are not in 'y'.
print(x.difference(y))

# Create a new frozenset with elements that are a union of 'x' and 'y' and print the result.
# This combines elements from both 'x' and 'y'.
print(x | y) 

Sample Output:

False                                                                                                         
frozenset({1, 2})                                                                                             
frozenset({1, 2, 3, 4, 5, 6, 7})  

Note:- Frozensets can be created using the function frozenset(). This datatype supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(), issuperset(), symmetric_difference() and union(). Being immutable it does not have method that add or remove elements.

Python Code Editor:

Previous: Write a Python program to remove all elements from a given set.
Next: Write a Python program to find maximum and the minimum value in a set.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.