List Comprehension Syntax

David Eppstein eppstein at ics.uci.edu
Thu Jul 22 13:45:51 EDT 2004


In article <cdohr3$680$1 at panix2.panix.com>, aahz at pythoncraft.com (Aahz) 
wrote:

> In article <HI7Ic.17372$1Z7.12975 at newssvr27.news.prodigy.com>,
> Moosebumps <crap at crap.crap> wrote:
> >
> >>>> result = [x for x in range(10) if x % 2 == 0 if x % 3 == 0]
> >>>> result
> >[0, 6]
> >>>> result = [ x*y for x in range(10) if x%2 == 0 for y in range(10) if y %
> >3 == 0]
> >>>> result
> >[0, 0, 0, 0, 0, 6, 12, 18, 0, 12, 24, 36, 0, 18, 36, 54, 0, 24, 48, 72]
> >
> >Just curious -- anyone care to tell me how they would format the above?  (or
> >maybe you wouldn't write it all)
> 
> Wouldn't use either.

I would probably use instead something like

>>> [x for x in range(0,10,6)]
[0, 6]
>>> [x*y for x in range(0,10,2) for y in range(0,10,3)]
[0, 0, 0, 0, 0, 6, 12, 18, 0, 12, 24, 36, 0, 18, 36, 54, 0, 24, 48, 72]

I think two for or if clauses in a comprehension is the most I'd want to 
use on a regular basis.  I certainly wouldn't use two ifs in a row as in 
your first example, I'd use and instead.

-- 
David Eppstein
Computer Science Dept., Univ. of California, Irvine
http://www.ics.uci.edu/~eppstein/



More information about the Python-list mailing list