if the else short form

BartC bc at freeuk.com
Thu Oct 7 12:56:53 CEST 2010

> On Thu, 07 Oct 2010 01:36:33 +0100, BartC wrote:

>> However,  as I mentioned, one problem here is having to evaluate all the
>> items in the list before selecting one:
>> x = {1 : fna(), 2 : fnb(), 3 : fnc()}.get(i, "None Of The Above")

"Mel" <mwilson at the-wire.com> wrote in message
news:i8j56e$ub8$1 at speranza.aioe.org...
> x = {1: fna, 2: fnb, 3: fnc}.get(i, lambda: "None Of The Above") ()

"Steven D'Aprano" <steve-REMOVE-THIS at cybersource.com.au> wrote in message
news:4cad1817$0$29996$c3e8da3$5496439d at news.astraweb.com...
> x = {1 : fna, 2 : fnb, 3 : fnc}.get(i, "None Of The Above")()

Well, these both kind of work (although the lambda thing is needed in the
second version, when i is out of range).

But you're both taking my example too literally; it was just my way of
testing whether or not each item was in fact evaluated.

In general, each item can be any arbitrary expression, which may or may not
include function calls.

To make this work as expected, I think 'lambda' is needed in front of every
expression, with the expressions written normally (so fn() instead of fn).

But with the syntax becoming more cumbersome, unintuitive, and with unknown
overheads to set up the lambda expressions (is it still necessary to
construct all dictionary entries?), it might be better to just use ordinary
conditional statements.


More information about the Python-list mailing list