List Comprehension Syntax

Moosebumps crap at crap.crap
Sun Jul 11 11:25:59 CEST 2004


> > Can you have multiple ifs at all?
>
> No, but you can have if (...) and (...) or (...)

Sure you can:

>>> 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]
>>>


It appears that you can have as many if's and for's as you like.

Just curious -- anyone care to tell me how they would format the above?  (or
maybe you wouldn't write it all)

MB





More information about the Python-list mailing list