(test) ? a:b

Chris Angelico rosuav at gmail.com
Wed Oct 22 18:40:53 CEST 2014


On Thu, Oct 23, 2014 at 3:28 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> It's also a technique easily extensible to more than two
> values:
>
>     '01TX'[n % 4]
>
> is in my opinion more readable than:
>
>     i = n % 4
>     '0' if i == 0 else '1' if i == 1 else 'T' if i == 3 else 'X'

That's true when it's fundamentally arithmetic. But part of that
readability difference is the redundancy in the second one. What if it
weren't so redundant?

'Negative' if x < 0 else 'Low' if x < 10 else 'Mid' if x < 20 else 'High'

You can't easily turn that into a dict lookup, nor indexing. It's
either a chained if/elif tree or nested if/else expressions, which
come to the same thing. So I'd say all the techniques have their
advantages and disadvantages. The most important thing to note is
where they differ in semantics, like the short-circuiting of if/else.

ChrisA



More information about the Python-list mailing list