if the else short form

BartC bc at freeuk.com
Thu Oct 7 02:36:33 CEST 2010



"Lawrence D'Oliveiro" <ldo at geek-central.gen.new_zealand> wrote in message 
news:i8j0dg$lh7$2 at lust.ihug.co.nz...
> In message <i8i1h8$dcl$1 at news.eternal-september.org>, BartC wrote:

>> x = ("One","Two","Three") [i-1]
>>
>> While this works for i = 1,2,3, it goes funny for i=0,-1,-2, and 
>> generates
>> an error for the rest ...
>
> x = {1 : "One", 2 : "Two", 3 : "Three"}.get(i, "None Of The Above")

Yes, I expected Python to come up with something (it always does).

However,  as I mentioned, one problem here is having to evaluate all the 
items in the list before selecting one:

def fna():
        print "FNA CALLED"
        return "One"
def fnb():
        print "FNB CALLED"
        return "Two"
def fnc():
        print "FNC CALLED"
        return "Three"

i=16
x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, "None Of The Above")
print x

Other than efficiency concerns, sometimes you don't want the extra 
side-effects.

Probably there are workarounds here too, but I suspect the syntax won't be 
quite as pert as the Algol68-style example:

x = (i | "Zero", "One", "Two" | "None of the above")      # 0-based

-- 
bartc 



More information about the Python-list mailing list