Idiosyncratic python

Steven D'Aprano steve at pearwood.info
Fri Sep 25 02:08:13 CEST 2015


On Fri, 25 Sep 2015 02:54 am, Todd wrote:

> Using list indexing with booleans in place of a ternary operator.
> 
> a = False
> b = [var2, var1][a]
> 
> Instead of:
> 
> b = var1 if a else var2

Ah, you youngsters...  :-)

Using a bool to index into a list used to be the standard idiom, before the
ternary if was added to the language. So I don't consider it "weird",
especially as a lot of my code still supports Python 2.4 which doesn't
include the ternary if.

Sometimes, instead of a list, I'll use a dict:

    {True: value1, False: value2}[flag]

to emulate ternary if.



-- 
Steven



More information about the Python-list mailing list