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

Diez B. Roggisch deets at nospam.web.de
Sun Jul 27 16:41:19 CEST 2008

DaveM schrieb:
> 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?

You obviously aren't aware of the pitfalls regarding the mis-use of or 
and and for this usage.

Try this:

 >>> a = True
 >>> b = 1
 >>> c = 2
 >>> a and b or c
 >>> a = False
 >>> a and b or c
 >>> a = True
 >>> b = None
 >>> a and b or c

> 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.

Can you tell us what you mean by "several names of one object"? You mean 

a = range(10)
b = a

id(a) == id(b)

? Passing references instead of values is an extremely important concept 
of many languages, without it you would end up copying most of the time.

> 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.

Any non-trivial task has that property. I don't know enough perl to have 
an example ready that shows something that python has only one way of 
doing and perl has several.

But I *do* know that taking the python zen literally is fruitless.


More information about the Python-list mailing list