Speaking of list-comprehension?

Andrew Durdin adurdin at gmail.com
Fri Jul 1 03:35:11 EDT 2005


On 7/1/05, Chinook <chinook.nr at tds.net> wrote:
> Thank you Andrew,  and your elaboration is well taken.  I was just
> exploring here and the construct you noted is IMHO intuitively readable
> - at least  for a simple  expression  and  condition.  Other than the
> choice order [False, True] which seems backward to me.

The choice order is based on the fact that True == 1 and False == 0
(as bool is a subclass of int). Also, I should probably have made the
choices a tuple instead of a list, if for no other reason than it's
slightly clearer:

>>> [tai + (10, -10)[tai >= 10] for tai in ta]
[15, 5, 2, 0, 19]

It may have a performance benefit as well, but (a) I haven't tested it
to see, and (b) it would be irrelevant for small lists like this
anyway.

One other thing I should have noted: unlike the ?: operator in
C/C++/Java, this construction (and the iif() function in my message)
will always evaluate both expressions, and does not short-circuit. In
many instances this is not necessary anyway.

 > So, where might I have found this construct.  It is probably somewhere
> obvious, but I searched and searched without success.  Of course, I've
> had only limited success in finding what I wanted in the "official'
> docs, though the QR has been quite useful.

It's in the "General Programming FAQ":
http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator



More information about the Python-list mailing list