# Comprehension with two variables - explanation needed

Rustom Mody rustompmody at gmail.com
Sun Nov 23 16:09:13 CET 2014

```On Sunday, November 23, 2014 8:28:16 PM UTC+5:30, Ivan Evstegneev wrote:
> Hello guys,
>
> I would like to ask you for some explanations on comprehensions. (Don't be scared, it just some particular example ^_^)
>
> I found this little "find prime number" example over the internet:
>
> >>> 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]
>
>
> It looked  pretty clear to me, till the time I decided to make some changes to it %)))
>
> Ok this is the case:
>
> As you can see the first line's comprehension produces a list, that includes all the multiplications of "i" (that range(2,8) ) in range (i*2, 50, i).
> So  I get this pattern: noprimes  = =  [4, 6, 8.....48, 6, 9,12.... ].
> The change that I tried to apply to this comprehension would lead to the following pattern: noprimes = = [[4, 6,8...48], [6, 9, 12....], ....,[some numbers]]
>
> But despite my struggling on it for the whole day, I haven't got to the desirable result(using comprehensions only)
>
> Please, don't get me wrong, I'm not a lazy one (just a beginner).
>
> In my case, I  made some googling, and found some patterns for matrices, that look this one(for example):
>
> Matrix = [[0 for x in range(5)] for x in range(5)]
>
> But when I tried to use square brackets with my code, it yields an error about definition of "i", for instance:
>
> File "<pyshell#30>", line 1, in <module>
> noprimes = [[j for i in range(2, 8)] for j in range(i*2, 50, i)]
> NameError: name 'i' is not defined.

Is this what you want?

>>> [[j for j in range(i*2, 50, i)] for i in range(2,8)]
[[4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48], [6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48], [8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48], [10, 15, 20, 25, 30, 35, 40, 45], [12, 18, 24, 30, 36, 42, 48], [14, 21, 28, 35, 42, 49]]

[I am not sure what you are trying -- just making local
changes to the ZF to make it work]

```