HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

What is better? For-loops or generator expressions (in cases like this)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thiswhatloopsexpressionsbettergeneratorlikeforcases

Problem

Which version of this code is better?

Ver 1.

a = 0
for i in xrange( 1000 ):
    if i % 3 == 0 or i % 5 == 0:
        a += i
print a


Ver 2.

from operator import add
print reduce( add,
              ( i for i in xrange( 1000 )
                if i % 3 == 0 or i % 5 == 0 ) )


Things I like about version one is that it is more readable, but it creates requires a variable. If you had to choose, which one would you argue is better?

Solution

The second version can (and should) be written using sum instead of reduce(add,...), which is somewhat more readable:

sum(i for i in xrange( 1000 ) if i % 3 == 0 or i % 5 == 0)


That is the version that I'd prefer as far as implementations of this particular algorithm go because it's more declarative than a loop and just reads nicer in my opinion. (It's also faster though that's less of a concern).

However it should be noted that for summing all numbers up to n that divisible by 3 or 5, there's actually a better algorithm than going over all those numbers and summing them.

Code Snippets

sum(i for i in xrange( 1000 ) if i % 3 == 0 or i % 5 == 0)

Context

StackExchange Code Review Q#6927, answer score: 8

Revisions (0)

No revisions yet.