Python Exercise: Frozensets

Python sets: Exercise-13 with Solution

Write a Python program to use of frozensets.

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

Sample Solution:-

Python Code:

x = frozenset([1, 2, 3, 4, 5])
y = frozenset([3, 4, 5, 6, 7])
#use isdisjoint(). Return True if the set has no elements in common with other. 
#use difference(). Return a new set with elements in the set that are not in the others.
#new set with elements from both x and y
print(x | y)

Sample Output:

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.

Pictorial Presentation:

Python Sets: Frozensets.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to clear a 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 Python skills with w3resource's quiz

Python: Tips of the Day

Returns True if there are duplicate values in a flat list, False otherwise


def tips_duplicates(lst):
  return len(lst) != len(set(lst))

x = [2, 4, 6, 8, 4, 2]
y = [1, 3, 5, 7, 9]