Donna Diana
Donna Diana

Reputation: 3

Write in one line

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

Answers (3)

vash_the_stampede
vash_the_stampede

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

G. Anderson
G. Anderson

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

Sufian Latif
Sufian Latif

Reputation: 13356

It would be

[str(num) for num in range(2000, 3201) if num % 7 == 0 and num % 5 == 0]

Upvotes: 0

Related Questions