Rant (was Re: x*x if x>10

Gary Herron gherron at islandtraining.com
Sun Jul 27 10:53:30 EDT 2008


DaveM wrote:
> On Sun, 27 Jul 2008 05:24:36 -0700 (PDT), alex23 <wuwei23 at gmail.com> wrote:
>
>   
>> On Jul 27, 10:13 pm, ssecorp <circularf... at gmail.com> wrote:
>>     
>>> I have seen somewhere that you can write something like:
>>>       
>
>   
>>> x*x if x>10
>>> but exactly that doesn't work and I can't get any variation to work.
>>>       
>
>   
>> It's called a ternary operator. The format is:
>> <label> = <true-value> if <condition> else <false-value>
>>     
>
> I've seen the PERL saying/motto/boast, "There's more than one way to do it"
> derided on more than one occasion on this group so what's the reason for
> this additional way to put an if else statement on one line? Are "and" and
> "or" constructions to produce the same effect not supported for this use?
>   

The "and" and "or" construct which is equivalent to the ternary operator 
is quite convoluted and looks nothing like a conditional computation:
   (C and [A] or [B])[0]
This is inefficient, and nearly unreadable, which makes the highly 
useful ternary operator worthy of a syntactical construct.


The [A], [B] and [0] parts are absolutely necessary in the general case 
where A can have values that Python would consider equivalent to False.  
If you know A will never be equivalent to False then  you can use just this:
    C and A or B

Gary Herron


> And while I'm on my high horse, I'd like to bring up list concatenations. I
> recently needed to concatenate 5 lists, which doesn't sound a particularly
> rare requirement to me. My first attempt was a straightforward loop
> extending an empty list. That worked fine but looked like an awful bulky
> solution. Afterwards I tried various formulae using "reduce" , falling foul
> of the "=" catch on one occasion. Now I'm not a professional programmer, so
> there may be good reasons for a single object to have multiple names in a
> program, but it sounds like a recipe for disaster to me. Getting back to the
> list concatenation, I finally found the itertools.chain command which is the
> most compact and fastest (or second fastest by a trivial amount, I can't
> remember which). Along the way, I must have tried/used half a dozen methods,
> ...which brings me back my initial PERL comment. There's more than one way
> to do it in Python, too.
>
> DaveM
> --
> http://mail.python.org/mailman/listinfo/python-list
>   




More information about the Python-list mailing list