Reputation: 3
Can the following code be written in one line:
for num in range(2000, 3201):
if num % 7 == 0 and num % 5 != 0:
nums.append(str(num))
I think of:
(nums.append(str(num))) for num in range(2000, 3201) if (num % 7 == 0) and (num % 5 != 0)
but it is not working
Upvotes: 0
Views: 83
Reputation: 4606
Note that if num % 7 == 0
is equivalent to if not num % 7
and if num % 5 != 0
is equivalent to if num % 5
nums = [str(num) for num in range(2000, 3201) if not num % 7 and num % 5]
Upvotes: 0
Reputation: 5955
You have it almost exactly right, exepct that you dont append in a list comprehension:
nums=[str(num) for num in range(2000, 3201) if (num % 7 == 0) and (num % 5 != 0)]
Upvotes: 2
Reputation: 13356
It would be
[str(num) for num in range(2000, 3201) if num % 7 == 0 and num % 5 == 0]
Upvotes: 0