We can pack multiple if-loops and if-else within a list generators.<br><br>Here is an example :<br>&gt;&gt;&gt; [i*j for i in range(1,10) for j in range(1,10) if i==j ]<br>[1, 4, 9, 16, 25, 36, 49, 64, 81]<br><br>Another one:<br>
&gt;&gt;&gt; noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]<br>&gt;&gt;&gt; primes = [x for x in range(2, 50) if x not in noprimes]<br>&gt;&gt;&gt; print primes<br>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]<br>
<br>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.<br>
example ( <a href="http://codepad.org/oshZLAbE">http://codepad.org/oshZLAbE</a> ), the code is crappy..made it just for the heck of it but want to know the syntax and the way of approaching.<br>