[Tutor] "if clause" in list comprehensions.

ALAN GAULD alan.gauld at btinternet.com
Wed Oct 21 11:57:23 CEST 2009



> Is the if-else (esp. 'else') in a list comprehension specific for Python 3.x? Or 
> did I miss something?


Its not part of list comprehensions per se, you can use it in any *expression*.
It was introduced in Python 2.5 as a response to C's ternary operator:

C:
 x = foo?bar:baz

Python
x = bar if foo else baz

So in the list comprehension case we are simply using that standard 
expression syntax as the value part of the LC.

HTH,

Alan G.


More information about the Tutor mailing list