Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sum function forloop

Tags:

python

sum

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
like image 992
Linus Svendsson Avatar asked Feb 12 '26 15:02

Linus Svendsson


2 Answers

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.

like image 145
Tim Pietzcker Avatar answered Feb 15 '26 05:02

Tim Pietzcker


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.

like image 21
Johnsyweb Avatar answered Feb 15 '26 07:02

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!