[BangPypers] A doubt in list comprehension

Shashwat Anand anand.shashwat at gmail.com
Sat Sep 12 04:54:01 CEST 2009

@srid: got it, thanks

normal codes are just nice, it's like i wanted to go through some
list-comprehension which makes the code a bit obsfucated. Atleast i should
be able to write my own and understand others.

Got a nice link too, wanted to share it :)

Thanks for the help !


A list comprehension has the following syntax:

[ *expression* for *target* in *iterable* *lc-clauses* ]

*target* and *iterable* are the same as in a regular for statement. You must
enclose the *expression* in parentheses if it indicates a tuple.

*lc-clauses* is a series of zero or more clauses, each with one of the
following forms:

for *target* in *iterable*
if *expression*

*target* and *iterable* in each for clause of a list comprehension have the
same syntax as those in a regular for statement, and the *expression* in
each if clause of a list comprehension has the same syntax as the *
expression* in a regular if statement.

courtesy ~

On Sat, Sep 12, 2009 at 7:48 AM, srid <sridhar.ratna at gmail.com> wrote:

> On Fri, Sep 11, 2009 at 4:57 PM, Shashwat Anand
> <anand.shashwat at gmail.com> wrote:
> > However what if I want an if-else loop in nested for loop.
> Are you referring to this:
>   ['EVEN' if x%2==0 else 'ODD' for x in range(10)]
> > for i in range(10):
> >     for j in range(10):
> >         for k in range(10):
> >             if i == j and j == k:
> >                 print "All equal"
> >             elif (i == j and j != k) or (i == k and j != k):
> >                 print "2 equal"
> >             else:
> >                 print "None equal"
> If you are asking how to achieve the above code using list
> comprehensions, then try
>    return ["All equal" if i==j and j==k else (
>                    "2 equal" if (i==j and j!=k) or (i==k and j!=k) \
>                            else "None equal")
>            for i in range(10)
>            for j in range(10)
>            for k in range(10)]
> For convenience, I pasted the code here: http://gist.github.com/185695
> Speaking personally, your original code is just fine - it is simpler
> than the list comprehension version above.
> -srid
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> http://mail.python.org/mailman/listinfo/bangpypers
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/bangpypers/attachments/20090912/98cd78ab/attachment-0001.htm>

More information about the BangPypers mailing list