# 16. Comprehending Comprehensions

#1
``````threes_and_fives = [x ** 1 for x in range(1, 16) if (x % 3 or x % 5)==0]
``````

Even though I got this section right, I wanted to know the issue with this code

#2

the condition you used here:

``````if (x % 3 or x % 5)==0
``````

isn’t right.

for example for `x=10` we get:

``````(10 % 3 or 10 % 5) == 0
``````

10 % 3 is 1, and 10 % 5 is zero so we get:

``````(1 or 0) == 0
``````

`1` is true (positive integers are considered true while zero is considered false)

so `1` is true, so `1 or 0` will evaluate to `1`, then we get:

``````1 == 0
``````

which is false, so `x` isn’t appended. (the if condition only appends when evaluate to true)

for `x=6` we would get:

``````(6 % 3 or 6 % 5 ) == 0
``````

which is:

``````(0 or 1 ) ==0
``````

`1` is true, so the `or` operator will pick the true value, so we get:

``````1 == 0
``````

which is false

the only reason `x=15` is working is because then you get `(0 or 0) == 0`, so there is no true value to pick for the or operator, so then it uses zero. `0 == 0` equals true. So finally something is appended to the list

But the most important thing, is to understand your if condition is wrong and needs fixing to work

for `or` and `and` operator, you need to compare at both sides of the `or` (or `and`) operator. Otherwise, you might get this unexpected behaviour.

#3

Thanks, I’ve gotten it now!

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.