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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With