else condition in list comprehension

Steven Bethard steven.bethard at gmail.com
Mon Jan 10 11:13:17 EST 2005


Luis M. Gonzalez wrote:
> It's me wrote:
>>> z = [i + (2, -2)[i % 2] for i in range(10)]
>>
>> But then why would you want to use such feature?  Wouldn't that make
>> the code much harder to understand then simply:
>>
>> z=[]
>> for i in range(10):
>>     if  i%2:
>>         z.append(i-2)
>>     else:
>>         z.append(i+2)
>>
>> Or are we trying to write a book on "Puzzles in Python"?
> 
> Once you get used to list comprehensions (and it doesn't take long),
> they are a more concise and compact way to express these operations.

After looking the two suggestions over a couple of times, I'm still 
undecided as to which one is more readable for me.  The problem is not 
the list comprehensions (which I love and use extensively).  The problem 
is the odd syntax that has to be used for an if/then/else expression in 
Python.  I think I would have less trouble reading something like:

     z = [i + (if i % 2 then -2 else 2) for i in range(10)]

but, of course, adding a if/then/else expression to Python is unlikely 
to ever happen -- see the rejected PEP 308[1].

Steve

[1] http://www.python.org/peps/pep-0308.html



More information about the Python-list mailing list