Linus Svendsson
Linus Svendsson

Reputation: 1477

python sum function forloop

I am just wondering.. How can I sum over different elements in a for loop?

for element in [(2,7),(9,11)] :
        g=sum(element[1]-element[0]+1)
        print g

If I remove 'sum', I get:

6
3

Upvotes: 2

Views: 3111

Answers (6)

John La Rooy
John La Rooy

Reputation: 304355

>>> sum(right-left+1 for left,right in [(2,7),(9,11)])
9

Upvotes: 2

OnesimusUnbound
OnesimusUnbound

Reputation: 2946

Is this what you refer?

g = 0
for element in [(2,7),(9,11)] :
         g= g + (element[1]-element[0]+1)
         print g 

sum only accepts iterable object

Update

g = 0
for element in [(2,7),(9,11)] :
         g += (element[1]-element[0]+1)
print g # moved indention to show the sum

Upvotes: 0

johnsyweb
johnsyweb

Reputation: 141858

You could replace this with a generator expression:

In [20]: sum(element[1] - element[0] + 1 for element in [(2, 7), (9, 11)])
Out[20]: 9

This could be simplified to:

In [21]: sum(y - x + 1 for x,y in [(2, 7), (9, 11)])
Out[21]: 9

...which I find easier to read and guarantees that each element in the list has exactly two elements. And it doesn't use unnecessary lambdas.

Upvotes: 3

Tim Pietzcker
Tim Pietzcker

Reputation: 336398

I'm not sure what you do want to get. Is it this?

>>> print sum(element[1]-element[0]+1 for element in [(2,7), (9,11)])
9

This generator expression is equivalent to

temp = []
for element in [(2,7), (9,11)]:
    temp.append(element[1]-element[0]+1)
print sum(temp)

but it avoids building a list in memory and is therefore more efficient.

Upvotes: 11

abuduba
abuduba

Reputation: 5042

The simplest way:

sum(map(lambda (x,y): y-x+1 , [(2,7),(9,11)]))

Upvotes: 1

pcalcao
pcalcao

Reputation: 15990

You can use a lambda function to map your list into a list of sums, something like this:

list_of_tuples = [(2,4),(5,7)]
list_of_sums = map(lambda x: x[0]+x[1], list_of_tuples)

There are many other ways of doing the same thing, but if you have never used map or lambda functions, it's a good opportunity to learn them ;)

Upvotes: 1

Related Questions