W3docs

if else in a list comprehension

Here's an example of using an if-else statement within a list comprehension:

Here's an example of using an if-else statement within a list comprehension:

if-else statement within a list comprehension

python— editable, runs on the server
Info

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]