Create a list of squares of even numbers and cubes of odd numbers from -5 to 5
This Python code creates a list called result using a list comprehension to calculate the square of even numbers and the cube of odd numbers in the range from -5 to 5. Here's how the code works:
- result = [x**2 if x % 2 == 0 else x**3 for x in range(-5, 6)] : This line of code initializes a variable named result and assigns it the result of a list comprehension.
- for x in range(-5, 6): This part sets up a loop that iterates through numbers from -5 to 5 (inclusive). The range(-5, 6) function generates a sequence of numbers starting from -5 and ending at 5.
- 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) or odd.
- [x**2 if x % 2 == 0 else x**3 for x in range(-5, 6)]: This is the list comprehension itself. It iterates through the numbers in the specified range (-5 to 5) 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(-5, 6)]
print(result)
Output
[-125, 16, -27, 4, -1, 0, 1, 4, 27, 16, 125]