6

I am generating tuples using :

Z = 1
W = 5
[(x,y) for x in range(Z-2,Z+2)for y in range(W-2,W+2)]

I would like to incorporate some boolean conditions to this generator such as :

  1. Don't include tuples where x equals y.
  2. Don't include tuples where x is non positive.

Is there a dedicated syntax for this task? Something like :

[(x,y) for x in range(Z-2,Z+2)for y in range(W-2,W+2) where (x!=y) and (x>0)]

Thanks!

2 Answers 2

13

I interpret non-positive numbers to include 0 so the conditions end up being

  1. x != y
  2. x >= 0

So the comprehension becomes:

>>> [(x,y) for x in range(Z-2,Z+2) for y in range(W-2,W+2) if x != y and x >= 0]
[(0, 3), (0, 4), (0, 5), (0, 6), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6)]

Another example: Select the numbers between 0 and 99 (inclusive) whose remainder of division for both 2 and 3 equals 0.

>>> [ i for i in range(100) if (i%2==0) and (i%3==0)]
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]

Generally you could describe the syntax as

[ result for variables in iterable if condition ]
Sign up to request clarification or add additional context in comments.

2 Comments

Every number divisible by 4 is divisible by 2, so there actually is no need for the first test since you're just producing multiples of 4. :P
@SukritKalra Good point faceplam I'll make a better example
0

you can use filter on the generator

filter (lambda i:i[0]!=i[1] and i[0]>0, ((x,y) for x in range(Z-2,Z+2)for y in range(W-2,W+2))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.