if else in a list comprehension
Here's an example of using an if-else
statement within a list comprehension:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squared_numbers = [x**2 if x % 2 == 0 else x for x in numbers]
print(squared_numbers)
Watch a video course
Python - The Practical Guide
This code creates a list numbers
containing the integers from 1 to 10, and then creates a new list squared_numbers
that contains the squares of the even numbers in numbers
, and the original numbers for the odd numbers. The output of this code would be: [1, 4, 3, 16, 5, 36, 7, 64, 9, 100]