Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

(a==b) ? 'Yes' : 'No'

1 view
Skip to first unread message

gentlestone

unread,
Mar 30, 2010, 11:40:56 AM3/30/10
to
Hi, how can I write the popular C/JAVA syntax in Python?

Java example:
return (a==b) ? 'Yes' : 'No'

My first idea is:
return ('No','Yes')[bool(a==b)]

Is there a more elegant/common python expression for this?

Mike Kent

unread,
Mar 30, 2010, 11:44:23 AM3/30/10
to

return ('Yes' if a == b else 'No')

Chris Rebert

unread,
Mar 30, 2010, 12:01:54 PM3/30/10
to gentlestone, pytho...@python.org

Yes, Python has ternary operator-like syntax:
return ('Yes' if a==b else 'No')

Note that this requires a recent version of Python.

Cheers,
Chris
--
http://blog.rebertia.com

Daniel Fetchinson

unread,
Mar 30, 2010, 12:17:04 PM3/30/10
to pytho...@python.org
>> Hi, how can I write the popular C/JAVA syntax in Python?
>>
>> Java example:
>> return (a==b) ? 'Yes' : 'No'
>>
>> My first idea is:
>> return ('No','Yes')[bool(a==b)]
>>
>> Is there a more elegant/common python expression for this?
>
> return ('Yes' if a == b else 'No')

And for less clutter you can even leave the parenthesis:

return 'Yes' if a == b else 'No'


--
Psss, psss, put it down! - http://www.cafepress.com/putitdown

John Nagle

unread,
Mar 30, 2010, 1:08:31 PM3/30/10
to

Who let the dogs in? That's awful syntax.

John Nagle

Joaquin Abian

unread,
Mar 30, 2010, 12:57:34 PM3/30/10
to

(a==b) and 'YES' or 'NO'

Yes, ugly

Joaquin

Robert Kern

unread,
Mar 30, 2010, 12:58:39 PM3/30/10
to pytho...@python.org

http://www.python.org/dev/peps/pep-0308/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Steven D'Aprano

unread,
Mar 30, 2010, 1:09:18 PM3/30/10
to
On Tue, 30 Mar 2010 08:40:56 -0700, gentlestone wrote:

> Hi, how can I write the popular C/JAVA syntax in Python?
>
> Java example:
> return (a==b) ? 'Yes' : 'No'
>
> My first idea is:
> return ('No','Yes')[bool(a==b)]

You don't need the call to bool.

('No','Yes')[a==b]


> Is there a more elegant/common python expression for this?

The above is pretty elegant to my eyes, but you can also do:

return 'Yes' if a==b else 'No'

--
Steven

Steven D'Aprano

unread,
Mar 30, 2010, 1:11:29 PM3/30/10
to
On Tue, 30 Mar 2010 10:08:31 -0700, John Nagle wrote:

>> Yes, Python has ternary operator-like syntax: return ('Yes' if a==b
>> else 'No')
>>
>> Note that this requires a recent version of Python.
>
> Who let the dogs in? That's awful syntax.

I used to think so to, but now I like it. It matches common English
syntax like:

"I'm going to the movies tonight, if I leave the office early, otherwise
I'll stay home and nitpick on Usenet."

--
Steven

Steve Holden

unread,
Mar 30, 2010, 1:56:04 PM3/30/10
to pytho...@python.org
Yes, that's deliberately awful syntax. Guido designed it that way to
ensure that people didn't aver-use it, thereby reducing the readability
of Python applications. Speaking purely personally I hardly ever use it,
but don't dislike it.


regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

Robert Kern

unread,
Mar 30, 2010, 2:05:13 PM3/30/10
to pytho...@python.org

I would suggest that this is much more common and less awkward English usage:
"If I leave the office early, I'm going to the movies tonight; otherwise, I'll

stay home and nitpick on Usenet."

I don't have a problem with the current syntax, and while its English analogue
is grammatical, I don't think you can rightly call it idiomatic.

Robert Fendt

unread,
Mar 30, 2010, 2:16:09 PM3/30/10
to
And thus spake Steve Holden <st...@holdenweb.com>
Tue, 30 Mar 2010 13:56:04 -0400:

> >> Yes, Python has ternary operator-like syntax:
> >> return ('Yes' if a==b else 'No')
> >>
> >> Note that this requires a recent version of Python.
> >
> > Who let the dogs in? That's awful syntax.
>
> Yes, that's deliberately awful syntax. Guido designed it that way to
> ensure that people didn't aver-use it, thereby reducing the readability
> of Python applications. Speaking purely personally I hardly ever use it,
> but don't dislike it.

In fact, the syntax just shouts 'do [...] unless' to me. And
that's so strong a Perl-ism I cannot quite express how ugly I
actually find it...

Regards,
Robert

John Bokma

unread,
Mar 30, 2010, 3:19:19 PM3/30/10
to
Robert Fendt <no....@local.local> writes:

> In fact, the syntax just shouts 'do [...] unless' to me. And
> that's so strong a Perl-ism I cannot quite express how ugly I
> actually find it...

And

a == b and 'Yes' or 'No'

isn't a Perl-ism?

Sheesh, this group would be so much nicer without the constant dragging
in of Perl to make a point. On top of that, do { } unless blocks are
not idomatic in Perl. Perl Best Practices even clearly states to *never*
use unless.

--
John Bokma j3b

Hacking & Hiking in Mexico - http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development

Pierre Quentel

unread,
Mar 30, 2010, 3:38:08 PM3/30/10
to
On 30 mar, 21:19, John Bokma <j...@castleamber.com> wrote:

I'm surprised nobody proposed a solution with itertools ;-)

- Pierre

Robert Fendt

unread,
Mar 30, 2010, 4:16:00 PM3/30/10
to
And thus spake John Bokma <jo...@castleamber.com>
Tue, 30 Mar 2010 13:19:19 -0600:

> And
>
> a == b and 'Yes' or 'No'
>
> isn't a Perl-ism?

I never said that this would be better. I don't even get the
point of what the advantage is supposed to be of inverting the
order of the return statement and the conditional check what
should actually _be_ returned. What's wrong with just writing

if a==b:
return 'Yes'
else:
return 'No'

apart from it being a few more line breaks and an additional
return statement? The inverted form is not more readable per
se (in fact, quite the opposite), and I would even suggest to
minimise its use even in languages like C++ and Java. The Python
syntax is even worse since it not only inverts the order of
return statement and conditional check, but it also puts the
conditional between the two results.

I find such a convoluted construct especially ugly in a language
which I previously regarded as having a rather striking beauty
of syntactical simplicity. The construct is superfluous,
illogical, unelegant, and thus very un-pythonesque, IMHO. But of
course that's just my $0.02.

> Sheesh, this group would be so much nicer without the constant dragging
> in of Perl to make a point. On top of that, do { } unless blocks are
> not idomatic in Perl. Perl Best Practices even clearly states to *never*
> use unless.

Sorry, but you have just underlined my point, in fact. If it's
discouraged by experts, then of course the question must be
valid why such a feature even exists (okay, apart from 'it
seemed like a good idea at the time'). And more importantly (and
more on-topic here), why we have to have an analogon in Python.

Regards,
Robert

Steve Holden

unread,
Mar 30, 2010, 4:32:51 PM3/30/10
to pytho...@python.org

It exists because people nagged Guido mercilessly until, against his
better judgment, he capitulated.

MRAB

unread,
Mar 30, 2010, 5:43:04 PM3/30/10
to pytho...@python.org
I think you mean that it's very _un-Pythonic_ (perhaps because it's very
very Pythonesque)! :-)

Robert Fendt

unread,
Mar 30, 2010, 5:47:27 PM3/30/10
to
And thus spake MRAB <pyt...@mrabarnett.plus.com>
Tue, 30 Mar 2010 22:43:04 +0100:

> I think you mean that it's very _un-Pythonic_ (perhaps because it's very
> very Pythonesque)! :-)

Yes. Of course. What was I thinking. ;-)

Regards,
Robert

Stephen Hansen

unread,
Mar 30, 2010, 6:17:28 PM3/30/10
to
On 2010-03-30 13:16:00 -0700, Robert Fendt said:
>
> I find such a convoluted construct especially ugly in a language
> which I previously regarded as having a rather striking beauty
> of syntactical simplicity. The construct is superfluous,
> illogical, unelegant, and thus very un-pythonesque, IMHO. But of
> course that's just my $0.02.

In Python before list-comprehensions, I might have agreed with you.
Initially, I was quite resistant to list comprehensions as well. They
seemed ugly, and backwards, and why not just write a for loop?

Then I got used to them, and I find they are very elegant when used
properly. Sometimes you can do something ugly with them, but its
actually quite possible to write positively hideous Python even without
any of these new fancy shmancy features.

But, in the post-comprehension world, where one can do:

my_odds = [x for x in range(100) if x % 2 == 1]

Things have changed. I've now grown used to reading expressions like
that which seem a bit backwards, with the value being returned by an
expression is the left-most element. Its not an exact correlation
because they're answering different problems.

But having gotten used to list comprehensions, and actually quite
appreciating their elegance now, I find this reads very well:

is_odd = "odd" if x % 2 == 1 else "even"

In fact, it reads better then any of the other conditional expression
syntaxes people proposed back in the day, and a LOT better then what
was done before:

is_odd = x % 2 == 1 and "odd" or "even"

Even if the above falls a bit more in line with what other languages
usually do order-wise, this isn't other languages.

Now, none of this addresses your original argument of why not just use
a regular if statement.

I dunno, I often used "and/or" for simple expressions or defaults and
found it very convienent and made code more readable then the line and
whitespace inducing true if-statement. And so I'm glad to have
something even more readable and without the bug-prone and/or error.

Why not just use a for loop anytime you use a list comprehension? :)
Same question really applies.

--
--S

... p.s: change the ".invalid" to ".com" in email address to reply privately.

Lawrence D'Oliveiro

unread,
Mar 30, 2010, 7:18:21 PM3/30/10
to
In message <7316f3d2-bcc9-4a1a-8598-

> (a==b) and 'YES' or 'NO'
>
> Yes, ugly

Why would you say that’s ugly?

By the way, you don’t need the parentheses.

Steve Holden

unread,
Mar 30, 2010, 7:43:41 PM3/30/10
to pytho...@python.org

But at the same time, if you don't *absolutely know* you don't need the
parentheses then the parentheses are a very good idea, so I applaud the
example as Pythonic while agreeing that it's ugly. A conditional
expression seems more natural.

John Bokma

unread,
Mar 30, 2010, 9:22:42 PM3/30/10
to
Robert Fendt <no....@local.local> writes:

> And thus spake John Bokma <jo...@castleamber.com>
> Tue, 30 Mar 2010 13:19:19 -0600:
>
>> And
>>
>> a == b and 'Yes' or 'No'
>>
>> isn't a Perl-ism?
>
> I never said that this would be better.

It was not my intention to imply you did. But yet I do see books on
Python mention the and or usage, and personally I think the ... if
... else is preferable.

> point of what the advantage is supposed to be of inverting the
> order of the return statement and the conditional check what
> should actually _be_ returned. What's wrong with just writing
>
> if a==b:
> return 'Yes'
> else:
> return 'No'

To me the else is adding unneeded noise, I would just write:

if a==b:
return 'Yes'

return 'No'

> apart from it being a few more line breaks and an additional
> return statement? The inverted form is not more readable per
> se (in fact, quite the opposite), and I would even suggest to
> minimise its use even in languages like C++ and Java. The Python
> syntax is even worse since it not only inverts the order of
> return statement and conditional check, but it also puts the
> conditional between the two results.

I use(d) the if ... else as follows (per Programming in Python 3):

list = [] if list is None else list

in Perl I would've written:

defined $list or $list = [];

Which I prefer over:

$list = [] unless defined $list;

and more over:

$list = [] if not defined $list;

To me the first Perl form reads as a pre-condition: the list must be
defined *or* make it so.

And maybe you're right, the Python one could've been written:

if list is None:
list = []

which looks, now, also more readable to me as well.

>> Sheesh, this group would be so much nicer without the constant dragging
>> in of Perl to make a point. On top of that, do { } unless blocks are
>> not idomatic in Perl. Perl Best Practices even clearly states to *never*
>> use unless.
>
> Sorry, but you have just underlined my point, in fact. If it's
> discouraged by experts, then of course the question must be
> valid why such a feature even exists (okay, apart from 'it
> seemed like a good idea at the time').

I guess the latter. Perl has quite some things that in retrospect
could've been done better. On the other hand, Perl developers are very
fanatic about backwards compatibility, which makes it hard to remove
stuff like unless.

On top of that Perl can't be statically analyzed, meaning you can't just
write a perl4to5 or perl510to512 converter.

> And more importantly (and
> more on-topic here), why we have to have an analogon in Python.

My point. You can sufficiently argue what's wrong with if..else in
Python 3 without dragging Perl into it and staying in Python context. I
am both a Perl and (learning) Python programmer, and to be honest I get
very tired of the somewhat weekly

omg Perl suxxxorsss!!11111

Each language has its own suckage. There are several reasons why while I
am learning Python I also keep updating my Perl skills ;-).

Russ P.

unread,
Mar 30, 2010, 10:18:50 PM3/30/10
to
On Mar 30, 10:08 am, John Nagle <na...@animats.com> wrote:
> Chris Rebert wrote:
> > On Tue, Mar 30, 2010 at 8:40 AM, gentlestone <tibor.b...@hotmail.com> wrote:
> >> Hi, how can I write the popular C/JAVA syntax in Python?
>
> >> Java example:
> >>    return (a==b) ? 'Yes' : 'No'
>
> >> My first idea is:
> >>    return ('No','Yes')[bool(a==b)]
>
> >> Is there a more elegant/common python expression for this?
>
> > Yes, Python has ternary operator-like syntax:
> > return ('Yes' if a==b else 'No')
>
> > Note that this requires a recent version of Python.
>
>      Who let the dogs in?  That's awful syntax.
>
>                                         John Nagle

Baloney. The Python ternary syntax is perfectly fine. The "if" could
have been put in front, as in Scala:

return if a == b "yes" else "no"

but either way is fine and perfectly readable as far as I am concerned.

Tim Chase

unread,
Mar 30, 2010, 10:25:13 PM3/30/10
to John Bokma, pytho...@python.org
John Bokma wrote:

> And maybe you're right, the Python one could've been written:
>
> if list is None:
> list = []
>
> which looks, now, also more readable to me as well.

Though there's a slight difference[1], I'd usually use

lst = lst or []

for your particular initialization use case.

-tkc

[1]
Difference being

>>> lst = []
>>> other = lst
>>> if lst is None: # your code
... lst = []
...
>>> other.append(42)
>>> lst, other
([42], [42])

>>> lst = []
>>> other = lst
>>> lst = lst or [] # my proposal
>>> other.append(42)
>>> lst, other
([], [42])

Peter Otten

unread,
Mar 31, 2010, 3:57:51 AM3/31/10
to
Pierre Quentel wrote:

> I'm surprised nobody proposed a solution with itertools ;-)

next(itertools.takewhile(lambda _: a == b, ["yes"]), "no")

You spoke to soon :)

Peter

TomF

unread,
Mar 31, 2010, 1:21:36 PM3/31/10
to

I salute you, sir, for upholding the standards of this group.

-Tom

Joaquin Abian

unread,
Mar 31, 2010, 3:11:18 PM3/31/10
to
On Mar 31, 1:18 am, Lawrence D'Oliveiro <l...@geek-
central.gen.new_zealand> wrote:
> In message <7316f3d2-bcc9-4a1a-8598-

>
> cdd5d41fd...@k17g2000yqb.googlegroups.com>, Joaquin Abian wrote:
> > (a==b) and 'YES' or 'NO'
>
> > Yes, ugly
>
> Why would you say that’s ugly?
>
> By the way, you don’t need the parentheses.

Lawrence,
maybe it was not the perfect adjective. I meant 'not beautiful'
because for me it is not an expression I can easily read. It is not
internalized in my brain. I know how to use it because I learnt how to
do it time ago(in Learning Python) but always I have to think how it
works (like a mental translation). For me the other alternative
expresion is more readable:

take_it if you_have_it else search_for_it

this was already in my brain before I started writing python code.
Thus, I prefer this option for my code. On the other hand, in my post,
I proposed the and/or style because I found interesting how
symmetrical it was with the one the OP was refering:

(a==b) ? 'Yes' : 'No'
(a==b) and 'Yes' or 'No'


I know, I could write it without parenthesis but it seems more
naturally organized with it and I read it faster and clearly. I dont
know exactly why but it seems also safer to me.

Joaquin

Den

unread,
Apr 1, 2010, 11:27:53 AM4/1/10
to
On Mar 30, 10:56 am, Steve Holden <st...@holdenweb.com> wrote:
> John Nagle wrote:
> > Chris Rebert wrote:
> >> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone <tibor.b...@hotmail.com>

I've been following this thread for a few days now. My thoughts are
that, in view of a long known widely used syntax for this operator,
python's syntax seems like change for change sake. If current
programing paradigm provides that particular trinary operator, why
should python's be different from the previously well known one.

For instance, no reasonable language designer would, now, use post-fix
(I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY.
(Just as no reasonable car designer would put the accelerator pedal on
the left.) There are conventions which should span products. Yes
python has the trinary operator and it's not going to change, but this
seems like a bit of petulance on the part of the designer.

Den

Steve Holden

unread,
Apr 1, 2010, 12:44:35 PM4/1/10
to pytho...@python.org
Den wrote:
[...]

> I've been following this thread for a few days now. My thoughts are
> that, in view of a long known widely used syntax for this operator,
> python's syntax seems like change for change sake. If current
> programing paradigm provides that particular trinary operator, why
> should python's be different from the previously well known one.
>
Because the "long known widely used syntax" has been responsible for
some of the most incomprehensible and buggy code in the known universe. \

> For instance, no reasonable language designer would, now, use post-fix
> (I know about Forth) or allow only +=, -=, /=, etc. assignments ONLY.
> (Just as no reasonable car designer would put the accelerator pedal on
> the left.) There are conventions which should span products. Yes
> python has the trinary operator and it's not going to change, but this
> seems like a bit of petulance on the part of the designer.
>
That argument could easily be extended to suggesting that there should
be no new languages at all. Guido made the specific choice of this
syntax precisely to try and ensure that the ternary (not trinary)
operator wasn't abused the way it has been in C (and later C#). He is a
language designer with a fine sense of readability, and I personally
respect his decision.

This StackOverflow thread

http://stackoverflow.com/questions/1763543/ternary-operator-associativity-in-c-can-i-rely-on-it

is just one example of the time that gets wasted.

But then I suppose that this thread just exemplifies that people will
find something else to waste their time on if you don't encourage them
to abuse the ternary operator.

Steven D'Aprano

unread,
Apr 1, 2010, 10:33:28 PM4/1/10
to
On Thu, 01 Apr 2010 08:27:53 -0700, Den wrote about Python's ternary
operator:

> I've been following this thread for a few days now. My thoughts are
> that, in view of a long known widely used syntax for this operator,
> python's syntax seems like change for change sake. If current
> programing paradigm provides that particular trinary operator, why
> should python's be different from the previously well known one.

Yes, I agree, we should be using the previously well known syntax:

condition -> value_if_true, value_if_false

which was introduced by BCPL in 1966.


> For instance, no reasonable language designer would, now, use post-fix
> (I know about Forth)

Do you also know about Postscript, Factor, Joy and Cat, to mention only a
few? And also the native language of Hewlett-Packard scientific
calculators, RPL.

> or allow only +=, -=, /=, etc. assignments ONLY.
> (Just as no reasonable car designer would put the accelerator pedal on
> the left.) There are conventions which should span products. Yes
> python has the trinary operator and it's not going to change, but this
> seems like a bit of petulance on the part of the designer.

Unless you have read the PEP that added the operator to the language, and
the reasons for rejecting the alternatives, you are not qualified to
guess what Guido's motives for choosing the current syntax are.

http://www.python.org/dev/peps/pep-0308/

You might not like it, but I do, and I like it far more than the ugly and
hard to understand C syntax. In English (which has existed for much
longer than C) the question mark punctuation symbol is a sentence
terminator, not a separator between clauses, so using ? as an operator
has always looked strange and disturbing to me.


--
Steven

Steve Howell

unread,
Apr 2, 2010, 12:16:18 AM4/2/10
to
On Mar 30, 8:40 am, gentlestone <tibor.b...@hotmail.com> wrote:
> Hi, how can I write the popular C/JAVA syntax in Python?
>
> Java example:
>     return (a==b) ? 'Yes' : 'No'
>
> ; first idea is:

>     return ('No','Yes')[bool(a==b)]
>
> Is there a more elegant/common python expression for this?

The ironic thing about the ternary operator is that it is not really
ternary; it's binary. Even just making an expression from a binary
operator inevitably leads to syntax hell.

There is a principle of programming that I would like to coin, which
is the "Tyranny of Three."

It is impossible to code for any expression that has three possible
values in any kind of elegant way. It's just impossible. Try to code
the bowling game without tearing out your teeth--three conditions:
strike, spare, or normal.

The tyranny of three is that 3 is too small for an elegant N-based
solution and too large for a simple condition.

Steven D'Aprano

unread,
Apr 2, 2010, 5:04:39 AM4/2/10
to
On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote:

> The ironic thing about the ternary operator is that it is not really
> ternary; it's binary. Even just making an expression from a binary
> operator inevitably leads to syntax hell.
>
> There is a principle of programming that I would like to coin, which is
> the "Tyranny of Three."
>
> It is impossible to code for any expression that has three possible
> values in any kind of elegant way. It's just impossible. Try to code
> the bowling game without tearing out your teeth--three conditions:
> strike, spare, or normal.
>
> The tyranny of three is that 3 is too small for an elegant N-based
> solution and too large for a simple condition.


I'm afraid I don't understand any of that. Can you explain further?

How is the ternary operator "not really ternary, it's binary"? It
requires three arguments, not two, which makes it ternary. In Python
syntax:

value1 if flag else value2

or in C:

flag ? value1 : value2

You say that "Even just making an expression from a binary operator

inevitably leads to syntax hell."

I don't understand what you mean. What is so hellish about any of these?

a + b # infix
a b + # postfix, familiar to anyone who has programmed HP calculators
add(a, b) # prefix function notation
+ a b # prefix
add a to b # verbose English-like


Well, perhaps the infix notation counts as "unusual", and the last as
"too verbose", but hellish?


--
Steven

Duncan Booth

unread,
Apr 2, 2010, 7:20:50 AM4/2/10
to
Steven D'Aprano <st...@REMOVE-THIS-cybersource.com.au> wrote:

> Yes, I agree, we should be using the previously well known syntax:
>
> condition -> value_if_true, value_if_false
>
> which was introduced by BCPL in 1966.
>

What, not this?

VALOF TEST condition THEN RESULTIS value_if_true ELSE RESULTIS
value_if_false

which was also introduced by BCPL in 1966.

:^)

Steve Howell

unread,
Apr 2, 2010, 10:05:49 AM4/2/10
to
On Apr 2, 2:04 am, Steven D'Aprano <st...@REMOVE-THIS-

cybersource.com.au> wrote:
> On Thu, 01 Apr 2010 21:16:18 -0700, Steve Howell wrote:
> > The ironic thing about the ternary operator is that it is not really
> > ternary; it's binary.  Even just making an expression from a binary
> > operator inevitably leads to syntax hell.
>
> > There is a principle of programming that I would like to coin, which is
> > the "Tyranny of Three."
>
> > It is impossible to code for any expression that has three possible
> > values in any kind of elegant way.  It's just impossible.  Try to code
> > the bowling game without tearing out your teeth--three conditions:
> > strike, spare, or normal.
>
> > The tyranny of three is that 3 is too small for an elegant N-based
> > solution and too large for a simple condition.
>
> I'm afraid I don't understand any of that. Can you explain further?
>
> How is the ternary operator "not really ternary, it's binary"? It
> requires three arguments, not two, which makes it ternary. In Python
> syntax:
>

Of course, I understand that the ternary operator has three arguments,
but it only has two possible outcomes.

You asked me to elaborate on the "Tyranny of Three." Let's say you
have three possible outcomes.

In some languages you would write something like this:

mark = (rolls == 1) && (pins == 10) ? 'strike' :
(rolls == 2) && (pins == 10) ? 'spare' :
'normal'

Many people consider the above very ugly, so they write it like so:

if pins == 10:
if rolls == 1:
return 'strike'
else:
return 'spare'
else:
return 'normal'

Then the next programmer comes along and "cleans up":

if pins == 10:
return 'strike' if rolls == 1 else 'spare'
else:
return 'normal'

Then there is this alternative:

if rolls == 2:
return 'spare' if pins == 10 else 'normal'
else:
return 'strike'

And then:

if rolls == 2:
if pins == 10
return 'spare'
else
return 'normal
else:
return 'strike'

Or even this:

return 'strike' if rolls == 1 else ('spare' if pins == 10 else
'normal')

The "Tyranny of Three" refers to a problem where there are an infinite
number of valid solutions, but none of them have any essential beauty,
so they lead to endless nitpicking and code churn.

Steve Holden

unread,
Apr 2, 2010, 10:21:52 AM4/2/10
to pytho...@python.org
Steve Howell wrote:
> On Apr 2, 2:04 am, Steven D'Aprano <st...@REMOVE-THIS-
> cybersource.com.au> wrote:
[...]

>> How is the ternary operator "not really ternary, it's binary"? It
>> requires three arguments, not two, which makes it ternary. In Python
>> syntax:
>>
>
> Of course, I understand that the ternary operator has three arguments,
> but it only has two possible outcomes.
>
That doesn't make it a binary operator. Otherwise what's long
multiplication, which has an infinite number of possible outcomes?

The Real Programmer (tm) simply chooses one, implements it and moves on.
While philosophical discussions are interesting they don't pay the bills.

Steve Howell

unread,
Apr 2, 2010, 10:26:19 AM4/2/10
to

I forgot this one:

def obfuscated_triager(rolls, pins,
lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare']
):
return lookup[rolls * pins]

Steve Howell

unread,
Apr 2, 2010, 10:31:06 AM4/2/10
to
On Apr 2, 7:21 am, Steve Holden <st...@holdenweb.com> wrote:
> Steve Howell wrote:
> > On Apr 2, 2:04 am, Steven D'Aprano <st...@REMOVE-THIS-
> > cybersource.com.au> wrote:
> [...]
> >> How is the ternary operator "not really ternary, it's binary"? It
> >> requires three arguments, not two, which makes it ternary. In Python
> >> syntax:
>
> > Of course, I understand that the ternary operator has three arguments,
> > but it only has two possible outcomes.
>
> That doesn't make it a binary operator. Otherwise what's long
> multiplication, which has an infinite number of possible outcomes?
>

Ok, it's not a binary operator. I just meant it only really selects
from two possible expressions, so you would think there would be one
good way to express that in code, but of course any variation of the
ternary operator leads to endless debates.

Agreed. The nitpicking and code churn tends to come up when you have
multiple programmers with different aesthetics, although sometimes
even the solo programmer can get overly fiddly.

Tim Chase

unread,
Apr 2, 2010, 10:52:36 AM4/2/10
to Steve Howell, pytho...@python.org
Steve Howell wrote:
> I forgot this one:
>
> def obfuscated_triager(rolls, pins,
> lookup = ['normal'] * 10 + ['strike'] + [None] * 9 + ['spare']
> ):
> return lookup[rolls * pins]

Bah...no need to be _quite_ so obscure:
def triager(rolls, pins):
return {
(1, 10):'strike',
(2,10):'spare',
(2,0):'wow, you stink',
}.get((rolls, pins), 'normal')


;-)

-tkc

Steve Howell

unread,
Apr 2, 2010, 10:58:14 AM4/2/10
to

Well played.

Steven D'Aprano

unread,
Apr 2, 2010, 12:00:47 PM4/2/10
to
On Fri, 02 Apr 2010 07:05:49 -0700, Steve Howell wrote:

>> How is the ternary operator "not really ternary, it's binary"? It
>> requires three arguments, not two, which makes it ternary. In Python
>> syntax:
>>
> Of course, I understand that the ternary operator has three arguments,
> but it only has two possible outcomes.

But the number of outcomes is not what the "binary" in binary operator
refers to. It's the number of arguments.


> You asked me to elaborate on the "Tyranny of Three." Let's say you have
> three possible outcomes.
>
> In some languages you would write something like this:
>
> mark = (rolls == 1) && (pins == 10) ? 'strike' :
> (rolls == 2) && (pins == 10) ? 'spare' :
> 'normal'

Not if you held a gun to my head *wink*


> Many people consider the above very ugly, so they write it like so:

[snip multiple alternative ways of choosing between three alternatives]

All very interesting, but I don't see why you are singling out three
alternatives as particularly difficult. Not all choices between three
possible results are hard to code:

choice = some_integer % 3 # returns 0, 1, or 2.

and choosing between two results isn't necessarily simple either, e.g.
the rules of protocol. Deciding which of two people outrank the other can
be *very* complicated. Does a king outrank a pope? What about a
president? Does a prince of some two-bit speck of dirt outrank a senator
of a superpower? People have worked out (by which I mean, "made up")
rules for all these and more, and they still can't always agree on who
ranks who. International negotiations have floundered and collapsed
because the parties couldn't agree which ambassador got the chair at the
head of the table nearest the door...

You are absolutely right to say that some problems don't have an elegant
solution, but I think you're wrong to single out "three" as special.


--
Steven

kj

unread,
Apr 2, 2010, 4:12:59 PM4/2/10
to

>John Nagle wrote:
>> Chris Rebert wrote:

>>> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone <tibor...@hotmail.com>


>>> wrote:
>>>> Hi, how can I write the popular C/JAVA syntax in Python?
>>>>
>>>> Java example:
>>>> return (a==b) ? 'Yes' : 'No'
>>>>

>>>> My first idea is:


>>>> return ('No','Yes')[bool(a==b)]
>>>>
>>>> Is there a more elegant/common python expression for this?
>>>

>>> Yes, Python has ternary operator-like syntax:
>>> return ('Yes' if a==b else 'No')
>>>
>>> Note that this requires a recent version of Python.
>>
>> Who let the dogs in? That's awful syntax.
>>
>Yes, that's deliberately awful syntax. Guido designed it that way to
>ensure that people didn't aver-use it, thereby reducing the readability
>of Python applications.

Is that for real??? It's the QWERTY rationale all over again. Swell.

"Let's preserve readability by making the syntax so ugly that people
won't use it."??? That's just perverse. (It would have been more
reassuring if the reason had been simply that Guido has an inexplicable
dislike of ternary expressions just like one may have an inexplicable
dislike of Broadway musicals.)

First, I don't understand why ternary expressions are inherently
hard to read, and therefore must be discouraged in the name of
overall code readability. Sure, one can write impenetrable ternary
expressions, but one can write impenetrable binary expressions or
impenetrable anything else, even in Python. That the expression
is ternary has nothing to do with it.

Second, sticking the test between the two alternatives goes against
a vast tradition in programming languages. This tradition inevitably
fosters habits and expectations when reading code, so going against
it automatically makes code less readable to all who were educated
in that tradition. Consider, for example, the readability of the
following if statement in some hypothetical language:

begin:
# this branch will be executed if test() (see below) evaluates
# to true
x = y + z
a = b * x + c
i = j - k
p = log(q)
if test() else:
x = -(y + z)
a = b * x + 2 * c
i = j + k
p = -log(q)

If you find this hard to read (I do), the quetion is "why?". For
me it's because, maybe through years of reading code, I've developed
a habit that says: when you run into a fork in the logic, first
understand what the decision hinges on. Therefore, my brain will
start hunting for that test, and it sucks to have to find it buried
somewhere in the middle. (Sure, one could justify this horrible
syntax with an argument reminiscent of the one you gave for "A if
X else B". It goes like this: long blocks of code should be avoided
in the name of readability; this syntax discourages long blocks of
code because one doesn't want to skip too far ahead to find that
test. Ergo the end result is improved readability. That's just
nuts.)

Anyway, I don't know of any other language that puts the test
between the alternatives. No doubt there's one out there, with
emphasis on "out there"...

~K

John Bokma

unread,
Apr 2, 2010, 4:20:06 PM4/2/10
to
kj <no.e...@please.post> writes:

> Anyway, I don't know of any other language that puts the test
> between the alternatives. No doubt there's one out there, with
> emphasis on "out there"...

Perl has something that has IMO somewhat the same problem:

print "Hello, world!\n" if $some_condition;

I prefer most of the time:

$some_condition and print "Hello, world!\n";

Or even:

$some_condition
and print "Hello, world!\n";

Moreover, instead of:

$x = 'some value' unless defined $x;

I prefer

defined $x
or $x = 'some value';

I read the latter as: $x must be defined, otherwise some value must be
assigned to it, like a precondition.

YMMV,

Steve Holden

unread,
Apr 2, 2010, 4:35:58 PM4/2/10
to pytho...@python.org
kj wrote:
> In <mailman.1326.1269971...@python.org> Steve Holden <st...@holdenweb.com> writes:
>
>> John Nagle wrote:
>>> Chris Rebert wrote:
>>>> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone <tibor...@hotmail.com>
>>>> wrote:
>>>>> Hi, how can I write the popular C/JAVA syntax in Python?
>>>>>
>>>>> Java example:
>>>>> return (a==b) ? 'Yes' : 'No'
>>>>>
>>>>> My first idea is:
>>>>> return ('No','Yes')[bool(a==b)]
>>>>>
>>>>> Is there a more elegant/common python expression for this?
>>>> Yes, Python has ternary operator-like syntax:
>>>> return ('Yes' if a==b else 'No')
>>>>
>>>> Note that this requires a recent version of Python.
>>> Who let the dogs in? That's awful syntax.
>>>
>> Yes, that's deliberately awful syntax. Guido designed it that way to
>> ensure that people didn't aver-use it, thereby reducing the readability
>> of Python applications.
>
> Is that for real??? It's the QWERTY rationale all over again. Swell.
>
I may be misrepresenting Guido here. Unlike Tim Peters I have never
claimed to be able to channel him.

> "Let's preserve readability by making the syntax so ugly that people
> won't use it."??? That's just perverse. (It would have been more
> reassuring if the reason had been simply that Guido has an inexplicable
> dislike of ternary expressions just like one may have an inexplicable
> dislike of Broadway musicals.)
>

I don't think his dislike of them is inexplicable. They do, when
over-used, lead to the most impenetrable code, which as a bonus is
frequently buggy.

> First, I don't understand why ternary expressions are inherently
> hard to read, and therefore must be discouraged in the name of
> overall code readability. Sure, one can write impenetrable ternary
> expressions, but one can write impenetrable binary expressions or
> impenetrable anything else, even in Python. That the expression
> is ternary has nothing to do with it.
>

I think it does - the scope of the expressions is inherently longer when
three terms are involved rather than just tow.

It's precisely to avoid that kind of lunacy that the chosen form was
adopted. Conditional expressions aren't *meant* to be complex enough to
leave any doubt about their meaning. If you require such complexity
that's perfectly OK - just use an "if" statement.

> Anyway, I don't know of any other language that puts the test
> between the alternatives. No doubt there's one out there, with
> emphasis on "out there"...
>

I understand you don't like it. The message handing down the decision is at

http://mail.python.org/pipermail/python-dev/2005-September/056846.html

and consideration of many applicable points in the standard library is at

http://mail.python.org/pipermail/python-dev/2005-September/056803.html

Disagree with the decision as you might, you can't argue that it was
made with insufficient consideration of the possible alternatives or the
merits of the solution.

Ethan Furman

unread,
Apr 2, 2010, 4:54:44 PM4/2/10
to pytho...@python.org
kj wrote:
> In <mailman.1326.1269971...@python.org> Steve Holden <st...@holdenweb.com> writes:
>
>> John Nagle wrote:
>>> Chris Rebert wrote:
>>>> On Tue, Mar 30, 2010 at 8:40 AM, gentlestone <tibor...@hotmail.com>
>>>> wrote:
>>>>> Hi, how can I write the popular C/JAVA syntax in Python?
>>>>>
>>>>> Java example:
>>>>> return (a==b) ? 'Yes' : 'No'
>>>>>
>>>>> My first idea is:
>>>>> return ('No','Yes')[bool(a==b)]
>>>>>
>>>>> Is there a more elegant/common python expression for this?
>>>> Yes, Python has ternary operator-like syntax:
>>>> return ('Yes' if a==b else 'No')
>>>>
>>>> Note that this requires a recent version of Python.
>>> Who let the dogs in? That's awful syntax.
>>>
>> Yes, that's deliberately awful syntax. Guido designed it that way to
>> ensure that people didn't aver-use it, thereby reducing the readability
>> of Python applications.
>
> Is that for real??? It's the QWERTY rationale all over again. Swell.

The rationale I remember is that it's intended primarily where the
condition is usually true, with the false only being once in a while.

[snip]

> Second, sticking the test between the two alternatives goes against
> a vast tradition in programming languages. This tradition inevitably
> fosters habits and expectations when reading code, so going against
> it automatically makes code less readable to all who were educated
> in that tradition.

So you're saying that new languages can't change anything already well
established? So much for break-through innovations.

And what about the programmers? It is good to learn to think in
different ways.

At any rate, I far prefer it over C's syntax.

~Ethan~

Patrick Maupin

unread,
Apr 2, 2010, 4:48:11 PM4/2/10
to
On Apr 2, 3:12 pm, kj <no.em...@please.post> wrote:
> Is that for real???  It's the QWERTY rationale all over again.  Swell.

Well, bearing in mind that everybody seems to have an agenda, so you
can't (or shouldn't, anyway) take all your news from a single source,
it may be that the common wisdom about the QWERTY thing is incorrect:

http://reason.com/archives/1996/06/01/typing-errors

I have to confess that I haven't done any real deep research on the
subject, but yet again, we find there is more than one side to a
story.

Regards,
Pat

Steven D'Aprano

unread,
Apr 2, 2010, 8:53:16 PM4/2/10
to
On Fri, 02 Apr 2010 20:12:59 +0000, kj wrote:

[...]


>>Yes, that's deliberately awful syntax. Guido designed it that way to
>>ensure that people didn't aver-use it, thereby reducing the readability
>>of Python applications.
>
> Is that for real??? It's the QWERTY rationale all over again. Swell.

Not according to the PEP. No fewer than 16 alternatives were put to a
vote, and with no clear winner (but many obvious losers) Guido made the
final decision.

http://www.python.org/dev/peps/pep-0308/

Although the results of the voting are given, unaccountably no final
tally was given. Possibly because nobody could agree on how to tally the
votes. Using a simple counting procedure (I give 3 votes for a rank1
vote, 2 votes for a rank2 and 1 for a rank3, signed according to whether
it was an Accept or Reject vote) I find the top four candidates were:

C. (if C: x else: y) 27%
D. C ? x : y 20%
B. if C then x else y 13%
A. x if C else y 11%

with everything else an order of magnitude smaller (6% or less). If you
choose a different voting scheme, no doubt you will get different results.

Since no candidate syntax got a majority of the vote, it came down to the
only vote that really mattered: Guido's.

Ankh-Morpork had dallied with many forms of government
and had ended up with that form of democracy known as
One Man, One Vote. The Patrician was the Man; he had the
Vote. -- (T. Pratchett, "Mort")


Guido did say "Note that all these are intentionally ugly" but this was
followed by a smiley and was obviously tongue-in-cheek.

http://mail.python.org/pipermail/python-dev/2005-September/056846.html


> "Let's preserve readability by making the syntax so ugly that people
> won't use it."??? That's just perverse. (It would have been more
> reassuring if the reason had been simply that Guido has an inexplicable
> dislike of ternary expressions just like one may have an inexplicable
> dislike of Broadway musicals.)

"Inexplicable"? They're musicals, and they're on Broadway. Surely that's
two good reasons to dislike them *wink*


> Second, sticking the test between the two alternatives goes against a
> vast tradition in programming languages.

As I've pointed out before, it is natural syntax in English. Not
necessarily the most common, but common enough to be completely
unexceptional:

"I'll be there in ten minutes, if I can find a parking space close by,
otherwise you should start without me."

--
Steven

Steve Howell

unread,
Apr 2, 2010, 11:18:59 PM4/2/10
to
On Apr 2, 5:53 pm, Steven D'Aprano <st...@REMOVE-THIS-

cybersource.com.au> wrote:
>
> As I've pointed out before, it is natural syntax in English. Not
> necessarily the most common, but common enough to be completely
> unexceptional:
>
> "I'll be there in ten minutes, if I can find a parking space close by,
> otherwise you should start without me."
>

To Steven's example, the ternary statement is a nice idiom when it
emphasizes the most common results:

wait_time = 10 if parking_space_close_by else
expected_wait_time_in_congested_area()

Or:

qoutient = m / n if n else None

In languages like Ruby/Perl the inverted if statement is also a useful
idiom to emphasize concisely that code is exceptional in nature:

def quotient(m, n)
# guard code
return None if n == 0

# happy path
return m / n
end


Or:

raise 'Armegeddon' if locusts_flying()
useful_intelligible_happy_path_code_here()

John Bokma

unread,
Apr 3, 2010, 1:44:42 PM4/3/10
to
Steve Howell <show...@yahoo.com> writes:

> In languages like Ruby/Perl the inverted if statement is also a useful
> idiom to emphasize concisely that code is exceptional in nature:
>
> def quotient(m, n)
> # guard code
> return None if n == 0
>
> # happy path
> return m / n
> end

Still, in Perl I prefer:

sub quotient {

my ( $m, $n ) = @_;
$n != 0 or return;

return $m / $n;
}

but I guess it depends a lot on what you're used to read.

Lawrence D'Oliveiro

unread,
Apr 3, 2010, 8:26:05 PM4/3/10
to
In message <mailman.1345.1269992...@python.org>, Steve
Holden wrote:

> Lawrence D'Oliveiro wrote:
>
>> By the way, you don’t need the parentheses.
>

> But at the same time, if you don't *absolutely know* you don't need the
> parentheses ...

But you can “abolutely know”—it’s all spelled out here
<http://docs.python.org/reference/expressions.html>. Just keep that page
open every time you write Python code.

Steven D'Aprano

unread,
Apr 3, 2010, 10:27:02 PM4/3/10
to

Or, when in doubt, you can add redundant parentheses. It makes no
difference to the runtime, and vanishingly small difference to the
compile-time, and sometimes it aids readability.

Writing the absolutely minimal code necessary to do what you want is not
necessarily the best approach in all cases. I find, for instance, that
redundant parentheses aid readability of complex logical and arithmetic
expressions, especially if you include whitespace.

--
Steven

Gregory Ewing

unread,
Apr 4, 2010, 8:08:31 PM4/4/10
to
Steven D'Aprano wrote:

> Not according to the PEP. No fewer than 16 alternatives were put to a
> vote, and with no clear winner (but many obvious losers) Guido made the
> final decision.

As I remember, the decision made on the basis of the vote
was *not* to add a conditional expression at all, because of
the fact that there was no clear winner.

It was some time later that Guido suddenly announced out of
the blue that he was accepting one of the choices that he had
earlier said he didn't like!

The ways of the BDFL are strange indeed. :-)

--
Greg

Steven D'Aprano

unread,
Apr 4, 2010, 8:19:12 PM4/4/10
to


I think what happened was the he got bitten by a subtle bug in the
previous idiom for the ternary operator:

condition and x or y

will return (x if condition else y) *unless* x itself happens to be a
false value. This demonstrated that the and/or idiom was not a suitable
alternative to a short-circuiting ternary operator.

--
Steven

Albert van der Horst

unread,
Apr 6, 2010, 10:16:17 AM4/6/10
to
In article <houv8a$ed9$02$2...@news.t-online.com>,
Peter Otten <__pet...@web.de> wrote:
>Pierre Quentel wrote:
>
>> I'm surprised nobody proposed a solution with itertools ;-)
>
>next(itertools.takewhile(lambda _: a == b, ["yes"]), "no")

I could learn something here, if you explain it?

>
>You spoke to soon :)
>
>Peter

Groetjes Albert

--
--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
albert@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

Albert van der Horst

unread,
Apr 6, 2010, 11:02:15 AM4/6/10
to
In article <mailman.1483.1270240...@python.org>,

Let's look at a c-example.
stamp = weight>=1000 ? 120 :
weight>=500 ? 100 :
weight>=250 ? 80 :
weight>=100 ? 60 :
44;

In a glance I see that stamp gets a value.
This wouldn't be so with regular if-statements that defines
numerous path's through the code that each must be tested.
Then I find this eminently suited to compare to a table given
as a specification.

What is akward is the definition of the ternary
operation that is left associative to mean
stamp = weight>=1000 ? 120 :
(
weight>=500 ? 100 :
(
weight>=250 ? 80 :
(
weight>=100 ? 60 :
44
)
)
) ;
And not

stamp = ((((( weight>=1000 ? 120 : weight>=500 ) ? 100 : weight>=250 )
? 80 ...

Now Python

stamp =( 120 if weight>=1000 else
100 if weight>=500 else
80 if weight>=250 else
60 if weight>=100 else
44 )

This has the same advantage as c, plus :
- the prices line up
- there is no way to misinterpret associativity
(anyway you put the brackets don't change meaning)

So I like it!
Old hands would have ...
stamp =( weight>=1000 and 120 or
weight>=500 and 100 or
weight>=250 and 80 or
weight>=100 and 60 or
44 )

(Kind of a brain twister, I think, inferior to C, once the c-construct
is accepted as idiomatic.)

<SNIP>

>
>regards
> Steve

Lie Ryan

unread,
Apr 6, 2010, 12:50:30 PM4/6/10
to
On 04/07/10 00:16, Albert van der Horst wrote:
> In article <houv8a$ed9$02$2...@news.t-online.com>,
> Peter Otten <__pet...@web.de> wrote:
>> Pierre Quentel wrote:
>>
>>> I'm surprised nobody proposed a solution with itertools ;-)
>>
>> next(itertools.takewhile(lambda _: a == b, ["yes"]), "no")
>
> I could learn something here, if you explain it?

The signature for next() is:
next(iterator[, default])

In particular, pay attention the `default` parameter.

next() returns `default` if StopIteration is raised else it returns
iterator.__next__().

takewhile(predicate, ["yes"]).__next__() return the string "yes" if
predicate("yes") returns True else it raises StopIteration.

The predicate (lambda _: a == b) returns True if (a == b) is True
otherwise it returns False.

Put the next(), takewhile(), and the predicate together and you get an a
monster that returns `default` if a == b is False else "yes".

Duncan Booth

unread,
Apr 6, 2010, 12:54:18 PM4/6/10
to
Albert van der Horst <alb...@spenarnc.xs4all.nl> wrote:

> Old hands would have ...
> stamp =( weight>=1000 and 120 or
> weight>=500 and 100 or
> weight>=250 and 80 or
> weight>=100 and 60 or
> 44 )
>
> (Kind of a brain twister, I think, inferior to C, once the c-construct
> is accepted as idiomatic.)

I doubt many old hands would try to join multiple and/or operators that
way. Most old hands would (IMHO) write the if statements out in full,
though some might remember that Python comes 'batteries included':

from bisect import bisect
WEIGHTS = [100, 250, 500, 1000]
STAMPS = [44, 60, 80, 100, 120]

...
stamp = STAMPS[bisect(WEIGHTS,weight)]

>>> map(lambda weight: STAMPS[bisect(WEIGHTS, weight)], [20, 100, 150, 999,
1000, 1100])
[44, 60, 60, 100, 120, 120]

Steven D'Aprano

unread,
Apr 7, 2010, 12:20:28 AM4/7/10
to
On Tue, 06 Apr 2010 16:54:18 +0000, Duncan Booth wrote:

> Albert van der Horst <alb...@spenarnc.xs4all.nl> wrote:
>
>> Old hands would have ...
>> stamp =( weight>=1000 and 120 or
>> weight>=500 and 100 or
>> weight>=250 and 80 or
>> weight>=100 and 60 or
>> 44 )
>>
>> (Kind of a brain twister, I think, inferior to C, once the c-construct
>> is accepted as idiomatic.)
>
> I doubt many old hands would try to join multiple and/or operators that
> way. Most old hands would (IMHO) write the if statements out in full,
> though some might remember that Python comes 'batteries included':
>
> from bisect import bisect
> WEIGHTS = [100, 250, 500, 1000]
> STAMPS = [44, 60, 80, 100, 120]
>
> ...
> stamp = STAMPS[bisect(WEIGHTS,weight)]


Isn't that an awfully heavyweight and obfuscated solution for choosing
between five options? Fifty-five options, absolutely, but five?

--
Steven

Duncan Booth

unread,
Apr 7, 2010, 4:15:38 AM4/7/10
to

I did say most people would simply write out an if statement.

However, since you ask, using bisect here allows you to separate the data
from the code and even with only 5 values that may be worthwhile.
Especially if there's any risk it could become 6 next week.


--
Duncan Booth http://kupuguy.blogspot.com

Emile van Sebille

unread,
Apr 7, 2010, 12:28:32 PM4/7/10
to pytho...@python.org
On 4/6/2010 9:20 PM Steven D'Aprano said...

Would it be easier to digest as:

from bisect import bisect as selectindex #

WEIGHTLIMITS = [100, 250, 500, 1000]
POSTAGEAMOUNTS = [44, 60, 80, 100, 120]

postage = POSTAGEAMOUNTS[selectindex(WEIGHTLIMITS, weight)]

---

I've used bisect this way for some time -- I think Tim may have pointed
it out -- and it's been handy ever since.

Emile


Aahz

unread,
Apr 12, 2010, 12:35:49 AM4/12/10
to
In article <mailman.1330.1269981...@python.org>,
Steve Holden <st...@holdenweb.com> wrote:
>
>It exists because people nagged Guido mercilessly until, against his
>better judgment, he capitulated.

No, the ternary exists because he became convinced that it was the
lesser evil compared with letting the abomination of

A and B or C

remain the "Pythonic" ternary and someone came up with a syntax that
wasn't completely painful.
--
Aahz (aa...@pythoncraft.com) <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan

Steven D'Aprano

unread,
Apr 12, 2010, 2:35:23 AM4/12/10
to
On Sun, 11 Apr 2010 21:35:49 -0700, Aahz wrote:

> In article <mailman.1330.1269981...@python.org>, Steve
> Holden <st...@holdenweb.com> wrote:
>>
>>It exists because people nagged Guido mercilessly until, against his
>>better judgment, he capitulated.
>
> No, the ternary exists because he became convinced that it was the
> lesser evil compared with letting the abomination of
>
> A and B or C
>
> remain the "Pythonic" ternary and someone came up with a syntax that
> wasn't completely painful.

As I recall, Guido himself got bitten by a subtle bug in the A and B or C
idiom for ternary operator. Namely, if B is a false value, you get C even
if A is true.


--
Steven

Dotan Cohen

unread,
Apr 19, 2010, 8:16:49 AM4/19/10
to gentlestone, pytho...@python.org
On 30 March 2010 18:40, gentlestone <tibor...@hotmail.com> wrote:
> Hi, how can I write the popular C/JAVA syntax in Python?
>
> Java example:
>    return (a==b) ? 'Yes' : 'No'
>
> My first idea is:
>    return ('No','Yes')[bool(a==b)]
>
> Is there a more elegant/common python expression for this?
>

I'm a little late to the party, but I just saw this in Dive Into Python:
multiple = 1024 if a_kilobyte_is_1024_bytes else 1000

It's kind of sloppy as the condition is between the possible values,
but it works.

--
Dotan Cohen

http://bido.com
http://what-is-what.com

Please CC me if you want to be sure that I read your message. I do not
read all list mail.

0 new messages