?: in Python

bonono at gmail.com bonono at gmail.com
Wed Dec 14 17:02:36 EST 2005


Andy Leszczynski wrote:
> How can do elegantly in Python:
>
> if condition:
>     a=1
> else:
>     a=2
>
> like in C:
>
> a=condition?1:2

a=(condition and [1] or [2])[0]

For this simple snippet, I don't think it is better than if/else, But
you can use it in map/reduce or list comprehension/generator expression.




More information about the Python-list mailing list