Reputation: 1477
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
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
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
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
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