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

Stephen Hansen apt.shansen at gmail.invalid
Tue Mar 30 18:17:28 EDT 2010


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.




More information about the Python-list mailing list