My Coding > Programming language > Python > Python FAQ > Python: How to use if/else in a list comprehension

Python: How to use if/else in a list comprehension

Use if/else in a list comprehension

List comprehension allow to use if/else construction in it. It is slightly different format for if and if/else pair in conditions.

List comprehension with if/else

The general syntax is as follows:


[fgood(x) if condition else fbad(x) for x in sequence]

The result of function fgood(x) will be added to the list in condition is True and fbad(x) will be added in other case for every elements in given sequence

List comprehension with if only

The syntax for only if condition is different in order:


[fgood(x) for x in sequence if condition]

The result of function fgood(x) will be added to a list if condition is True. Otherwise, if the element is not produce True in the condition, this element will not be send to the function fgood(x) and the result derived from this element will not be added to the list for every elements in given sequence.


Published: 2021-10-14 04:13:13

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.