Python program: Frozenset of squares of odd numbers

Python Frozenset Views Data Type: Exercise-10 with Solution

Write a Python program that generates a frozenset containing the squares of all odd numbers from 1 to 15 using set comprehension.

Sample Solution:


def main():
    odd_numbers = {x**2 for x in range(1, 16) if x % 2 != 0}
    frozenset_of_squares = frozenset(odd_numbers)
    print("Frozenset of Squares of Odd Numbers:", frozenset_of_squares)

if __name__ == "__main__":


Frozenset of Squares of Odd Numbers: frozenset({1, 121, 225, 9, 169, 81, 49, 25})

In the exercise above, we use a set comprehension to generate a set of squares of odd numbers from 1 to 15. The 'odd_numbers' set comprehension iterates through the range of numbers and filters out only the odd numbers using the condition x % 2 != 0. Based on the result of the set comprehension, we create a 'frozenset' named 'frozenset_of_squares'.

Finally, the program prints the 'frozenset' containing odd-numbered squares.


Flowchart: Python program: Frozenset of squares of odd numbers .

Previous: Hashable composite keys using frozenset: Python code example.

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.