mounaim
mounaim

Reputation: 1180

Is it possible to use for loops inside print statement in Python

Can I use print elements in a for loop with some conditions ?
Actually I have this block of code :

sum = 0
for i in range(1,1000):
    if i%3 == 0 or i%5 == 0 :
        sum+=i
print(sum)  

and I want to convert it in a single line of code. Any help would be greatly appreciated.

Upvotes: 1

Views: 20392

Answers (2)

James Sapam
James Sapam

Reputation: 16940

Using reduce and lambda:

>>> reduce( lambda x,y: x +y, [i for i in range(1000) if i % 3 == 0 or i % 5 == 0 ])
233168 
>>>

Or If you want variable condition:

>>> def sum_it(Range, Divisible_by):
...    return sum([[0, i][any([i % n == 0 for n in Divisible_by])] for i in range(Range)])
...
>>> sum_it(1000, [3,5])
233168
>>> sum_it(1000, [3,6])
166833
>>>

Upvotes: 1

arshajii
arshajii

Reputation: 129547

You can use a generator expression:

print(sum(i for i in range(1,1000) if i%3 == 0 or i%5 == 0))

Note that I'm using the built-in function sum() here, which is different than you variable sum (in general you shouldn't use that as a name since it shadows the built-in function).

Upvotes: 8

Related Questions