I have wrote following code for a simple problem in Python –
def Peu1(numbers):
"Sum of all the multiples of 3 or 5 below 1000."
for num in range(numbers):
if num%3 == 0 or num%5 == 0:
test = sum(range(numbers),0)
return test
print Peu1(1000)
I want to change it to List comprehension, I wrote following –
test = [sum(range(numbers),0) for num in range(numbers) if num%3 == 0 or num%5 == 0]
print test
but my list comprehension is printing result in a loop, I mean I am getting result n times(mod 3 or 5). Please pinpoint the mistake and guide.
A list comprehension is designed to build up a list – if you are not doing that, then you don’t need to use one.
You could, however, use a list comprehension or generator expression inside your function, to generate the list of numbers to use:
Note that
numbersis a bit of a misleading variable name – it would imply to me that it contained the range of numbers, I’d suggest either passing in the range of numbers, or calling ithighestor something.Rather than using the or with the same value, some people find something like
if 0 in {num%3, num%5}clearer, personally, I think in this case it obscures the meaning a little.