if/else in a list comprehension
Here is an example of using an if/else statement in a list comprehension in Python:
# Create a list of numbers from 1 to 10
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use a list comprehension to create a new list with the even numbers squared and the odd numbers cubed
result = [x**3 if x % 2 == 1 else x**2 for x in numbers]
print(result) # Output: [1, 4, 27, 16, 125, 36, 343, 64, 729, 100]
Watch a video course
Python - The Practical Guide
In this example, we use a list comprehension to iterate over the numbers in the "numbers" list. For each number, we use an if/else statement to check if it is odd (x % 2 == 1) or even. If it is odd, we cube it (x3). If it is even, we square it (x2). The result is a new list with the modified values.