Reputation: 3
I have two lists
a=[1,2,3,4]
b=[5,6,7]
What I want is to find the sum of each element in both the lists and store the sum to another variable, i.e
1+2+3+4+5+6+7=28
and store it to any variable.
My code:
for i in range(0,len(od)):
s=s+od[i]
v=s
for i in range(0,len(ed)):
v=v+ed[i]
print(v)
I have found the sum by this method. Is there any other method which will be shorter and more pythonic?
Upvotes: 0
Views: 187
Reputation: 3
Addition to @João Haas Answer you can process in a different way also. contact a list first then compute the sum
v = sum(od + ed)
Upvotes: 0
Reputation: 21
The sum() function returns a number, the sum of all items in an iterable.
Basically you just have to add the sum of both of your lists
v = sum(od) + sum(ed)
Upvotes: 0
Reputation: 2132
https://docs.python.org/3/library/functions.html#sum
You could write this code as:
v = sum(od) + sum(ed)
EDIT: As a side note, the way you're doing item iteration is not 'pythonic' as well. On most languages you access array items using indexes (the [i]
part), but on python, the ideal way to iterate an array is by getting the values directly.
So, if you wanted to follow the same structure as the initial code, the 'pythonic' way to write it would be something like this:
result = 0
for value in od:
result += value
for value in ed:
result += value
print(result)
Upvotes: 3