[BangPypers] A doubt in list comprehension

Shashwat Anand anand.shashwat at gmail.com
Sat Sep 12 01:57:47 CEST 2009


We can pack multiple if-loops and if-else within a list generators.

Here is an example :
>>> [i*j for i in range(1,10) for j in range(1,10) if i==j ]
[1, 4, 9, 16, 25, 36, 49, 64, 81]

Another one:
>>> noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
>>> primes = [x for x in range(2, 50) if x not in noprimes]
>>> print primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

The first code print squares and second print primes until 50. First code
show a nested for-loop in list-comprehension and second code shows a
multiple if-else loop in noprimes[] and for-loop with an if-loop in prime[].
However what if I want an if-else loop in nested for loop.
example ( http://codepad.org/oshZLAbE ), the code is crappy..made it just
for the heck of it but want to know the syntax and the way of approaching.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/bangpypers/attachments/20090912/19856508/attachment.htm>


More information about the BangPypers mailing list