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


This Python code creates a list called result using a list comprehension to calculate either the square or the cube of numbers from 1 to 10 based on whether they are even or odd. Here's how the code works:

  • result = [x**2 if x % 2 == 0 else x**3 for x in range(1, 11)] : This line of code initializes a variable named result and assigns it the result of a list comprehension.
    • for x in range(1, 11): This part sets up a loop that iterates through numbers from 1 to 10 (inclusive). The range(1, 11) function generates a sequence of numbers starting from 1 and ending at 10.
    • x**2 if x % 2 == 0 else x**3: For each value of x in the range, this expression calculates either the square (x**2) or the cube (x**3) of the number based on whether x is even (x % 2 == 0). If x is even, it calculates the square; otherwise, it calculates the cube.
    • [x**2 if x % 2 == 0 else x**3 for x in range(1, 11)]: This is the list comprehension itself. It iterates through the numbers in the specified range (1 to 10) and, for each number, calculates either its square or cube based on whether it's even or odd. The results are collected into a new list.
  • print(result): This line of code prints the result list to the console.

Source Code

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

Output

[1, 4, 27, 16, 125, 36, 343, 64, 729, 100]

Example Programs