else condition in list comprehension

Luis M. Gonzalez luismgz at gmail.com
Mon Jan 10 10:49:53 EST 2005

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
> 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.
I think that writing 6 lines instead of 1 could be more readable of you
are a beginner, but after playing a little bit with listcomps for the
first time, you'll see they are very practical yet readable.

More information about the Python-list mailing list