list comprehension question

alex23 wuwei23 at gmail.com
Wed May 6 05:36:37 CEST 2009


On May 6, 4:01 am, "J. Cliff Dyer" <j... at sdf.lonestar.org> wrote:
> The way you have to bounce your eyes back and forth in the comprehension
> makes it hard to read the logic.  With the loop, on the other hand it is
> blatantly obvious which way the nesting occurs.

> > >>>> [ item for j in a if len(j)==2 for item in j if item % 2 ]
> > > ...opposed to...
> > >>>> for j in a:
> > > ...     if len(j)==2:
> > > ...         for item in j:
> > > ...             if item % 2:
> > > ...                 b.append(item)
> > > ...

> Much nicer.  Thank you.

Apart from the presence of 'item' at the beginning of the list
comprehension as opposed to 'b.append(item)' at the end of the for-
loop, how exactly does the listcomp force you to "bounce [..] back and
forth" to follow the logic? The only other difference between the two
is in the layout - the indentation & colons - otherwise they're
structurally identical.



More information about the Python-list mailing list