Skip to content

Python list comprehension if else | Example code

  • by

You can use if-else in list comprehension to Conditional Outputs in Python. Do something if, else do something else.

[output if condition else output for l in list]

Note: Use both if and else keywords otherwise a SyntaxError is thrown and elif does not apply here.

Python example if/else in a list comprehension

Simple example code.

Creates a list from 0 to 9 through a list comprehension which iterates through the list and outputs either ‘0’ or ‘1’ for every number in the list. We use the modulo (%) operator that returns the remainder of a division.

A number is ‘0’ if the remainder of the division by 5 is 0, otherwise, the number is ‘1’.

nums = list(range(10))
num_classes = [0 if num % 5 == 0 else 1 for num in nums]


Python list comprehension if else

Another example: Conditionals in List Comprehension

Using if with List Comprehension to create the list by the items in range from 0-19 if the item’s value is divisible by 2.

number_list = [x for x in range(20) if x % 2 == 0]


Output: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Nested IF with List Comprehension

If y satisfies both conditions, y is appended to num_list.

num_list = [y for y in range(50) if y % 2 == 0 if y % 5 == 0]

Output: [0, 10, 20, 30, 40]

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *