Summing elements in a list using Python

Posted by Samath
  1003
March 04, 2015

 

Write a function sumlist that takes a list and a function as input, applies the function to each element of the list, and returns the sum. Use a for loop for traversing through the elements in the list and accumulate the sum.

[Hint: Remember how for loops worked with range.
for i in range(15,18):
First time we enter the loop i will be 15, then 16 and finally 17.

Note instead of range we can actually use the list that is being entered as an argument.
for i in ls:
If ls = [15,16,17], first time we enter the loop i will be 15, then 16 and finally 17.]

For example, assuming that square and cube have been defined already, you would observe the following:

>>>sumlist([1,2,3],square)
14
>>>sumlist([1,2,3],cube)
36
>>>sumlist([1,2,3],lambda x : x)
6

Code:

def sumfunc(num):
     return num

def sumlist(mylist, sumfunc):
    sum = 0
    for i in mylist:
        sum = sum + sumfunc(i)
    return sum