Summing elements in a list using Python
###### Posted by Samath
Last Updated: 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```

###### How can you find the sum of elements in a list using list comprehension in Python?
DavidLee | Aug 20, 2024
###### How can you find the sum of elements in a list using a list of functions in Python?
OliviaWm | Aug 12, 2024
###### How do you count the frequency of elements in a list in Python?
SamPetr | Aug 10, 2024
###### How can you find the maximum and minimum elements in a list in Python?
CarolTh | Aug 15, 2024
###### How do you rotate a list by k elements in Python?
KarenKg | Aug 28, 2024
###### How can you find the sum of elements in a list using recursion in Python?
MaryJns | Aug 19, 2024
###### How can you find the sum of squares of elements in a list in Python?
KarenKg | Aug 16, 2024
###### Write a Python function to find the product of all elements in a list.
FrankMl | Aug 16, 2024
###### How do you find the sum of elements in a list using a loop in Python?
FrankMl | Aug 13, 2024
###### How can you find the sum of elements in a list using a reduce function in Python?
BobHarris | Aug 08, 2024
###### How can you find the sum of elements in a list using a while loop in Python?
HenryPk | Aug 18, 2024
###### How can you find the sum of elements in a list using a for loop in Python?
EveClark | Aug 17, 2024
###### How can you find the sum of elements in a list using the sum() function in Python?
QuinnLw | Aug 19, 2024
###### How can you find the sum of elements in a list using a generator in Python?
TinaGrn | Aug 30, 2024