Create a set of even numbers squared and odd numbers cubed from 1 to 10


This Python code uses a set comprehension to create a set named result. The set contains the squares of even numbers and the cubes of odd numbers in the range from 1 to 10. Here's how the code works:

  • result = {x**2 if x % 2 == 0 else x**3 for x in range(1, 11)}: This line initializes a set named result using a set comprehension.
    • for x in range(1, 11): This part of the code sets up a loop that iterates through the numbers from 1 to 10 (inclusive).
    • {x**2 if x % 2 == 0 else x**3}: For each number x, this part calculates the square (x**2) if x is even (i.e., if x % 2 == 0 is true), and it calculates the cube (x**3) if x is odd.
  • print(result): This line of code prints the result set to the console.

Source Code

result = {x**2 if x % 2 == 0 else x**3 for x in range(1, 11)}
print(result)

Output

{64, 1, 4, 36, 100, 16, 343, 729, 27, 125}

Example Programs