W3docs

if/else in a list comprehension

Here is an example of using an if/else statement in a list comprehension in Python:

Here is an example of using an if/else statement in a list comprehension in Python:

Using an if/else statement in a list comprehension in Python

python— editable, runs on the server
Info

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.