What is the value of pairs after the following assignment?
pairs=[(x,y) for x in range(4) for y in range(3) if (x+y)%3==0]
1
Expert's answer
2018-09-14T07:41:01-0400
The value of pairs after execution of code: pairs=[(x,y) for x in range(4) for y in range(3) if (x+y)%3==0] is [(0, 0), (1, 2), (2, 1), (3, 0)]
Explanation: for x in range(4) is outer loop and for y in range(3) is inner loop. The variable x is changed from 0 to 3 and variable y is changed from 0 to 2. The values are added to the list pairs only if this statement: if (x+y)%3==0 is True. The % is modulus operator that divides left operand (x+y) by right operand 3 and returns the remainder. The sum of (x+y) should be 0 or 3 to make the statement True. The resulting variable pairs is a list of tuples.
The expression is equivalent to the following code: pairs = [] for x in range(4): for y in range(3): if (x + y) % 3 == 0: pairs += [(x, y)]
Comments
Leave a comment