the PHP ternary operator equivalent on Python

bonono at gmail.com bonono at gmail.com
Sat Nov 19 02:19:47 EST 2005


Steven D'Aprano wrote:
> Why do you assume that everything you need for your list comprehension has
> to go into a single line? Chances are your list comp already calls
> functions, so just create one more for it to use.
>
>
> py> def describe(cond):
> ...     if cond:
> ...         return "odd"
> ...     else:
> ...         return "even"
> ...
> py> L = [describe(n % 2) for n in range(8)]
> py> L
> ['even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd']

this makes me "jump" from the list comprehension to the function,
harder to follow than 'in place', especially when the function is
simple, it is not necessary. What is the reason for introducing list
comprehension and then later, generator expression when :

a=[]
for x in range(8):
  a.append(describe(x%2))
return a

and

for x in range(8):
  yield describe(x%2)

can do the same thing ?

Doesn't it violate the general idiom that it better has one and only
one way to do certain thing ? I believe part of the reason is that one
doesn't need to "jump" up and down.

>
> One major advantage is that this makes it easier to test your function
> describe() in isolation, always a good thing.
>
> Another advantage is that the idiom "call a function" is extensible to
> more complex problems:
>
> def describe(n):
>     if n < 0:
>         return "negative " + describe(-n)
>     elif n == 0:
>         return "zero"
>     elif n % 2:
>         return "odd"
>     else:
>         return "even"
>
> L = [describe(n) for n in range(8)]
>
> if much easier to understand and follow than using ternary expressions:
>
> # obviously untested
> L = ["zero" if n == 0 else \
>     "negative " + ("odd" if n % 2 else "even") if n < 0 else \
>     "odd" if n % 2 else "even" for n in range(8)]
>
> Yes, I've seen ternary expressions nested three and even four deep.
Now that is obsession for(and bad use of) one-liner. But picking a bad
example of one liner to rule out its effectiveness and readability is a
stretch I would say.




More information about the Python-list mailing list