Can I use a conditional in a variable declaration?

andy andy at wild-flower.co.uk
Sun Mar 19 13:12:37 CET 2006


volcs0 at gmail.com wrote:

>I've done this in Scheme, but I'm not sure I can in Python.
>
>I want the equivalent of this:
>
>if a == "yes":
>   answer = "go ahead"
>else:
>   answer = "stop"
>
>in this more compact form:
>
>
>a = (if a == "yes": "go ahead": "stop")
>
>
>is there such a form in Python? I tried playing around with lambda
>expressions, but I couldn't quite get it to work right.
>
>  
>
How about:

a = ["stop","go ahead"][a == "yes"]

This works because:

>>> int("yes" == "yes")
1
>>> int("yes" == "no")
0

Taking into account all the previous comments - both the literal list
elements are evaluated; there is no short-cirtuiting here. If they're
just literals, it's no problem, but if they're (possibly
compute-intensive) function calls, it would matter. I find the list
evaluation easier to parse than the and/or equation, and in instances
where that would be necessary, I will use the longhand if ... else ...
structure for readability.

hth,
-andy



More information about the Python-list mailing list