The ternaery operator

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Thu Mar 16 11:55:56 EDT 2017


William Mayor writes:

>> I think it would be nice to have a way of getting the 'true' value as
>> the return with an optional value if false.  The desire comes about
>> when the thing I'm comparing is an element of a collection:
>> 
>>        drugs['choice'] if drugs['choice'] else 'pot'
>> 
>> Then I'm tempted to do:
>> 
>> 	chosen = drugs['choice']
>> 	chosen if chosen else 'pot'
>> 
>> I sometimes feel like doing:
>> 
>> 	drugs['choice'] else 'pot'
>> 
>
> For the case where the element in the collection exists, but might be
> falsey you could do:
>
> 	drugs[‘choice’] or ‘pot'

drugs.get('choice') or 'pot'

drugs.get('choice', 'pot')

[snip]


More information about the Python-list mailing list