Home »
Python »
Python Programs
Python program to find the sum of elements of a list using lambda function
Here, we will write a Python program to find the sum of elements of a list using lambda function.
Submitted by Shivang Yadav, on March 19, 2021
Lambda functions in Python are special functions available in python. They are anonymous functions i.e., without any function name.
Here, we will find the sum of all elements of the list using the lambda function.
Program to find the sum of all elements of the list
# Python program to find the sum of all elements of the list
# function to find the sum of elements of list
def add(data):
s=0
for n in data:
s=s+n
return s
# List of some fibonacci numbers
fiboList = [0,1,1,2,3,5,8,13,21,34,55]
print("List of fibonacci numbers :",fiboList)
# calling function to add elements of fibonacci list
listSum = add(fiboList)
print("The sum of all elements is ",listSum)
Output
List of fibonacci numbers : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
The sum of all elements is 143
Program to find the sum of all elements using lambda function
# Python program to find the sum of
# all elements of the list
from functools import reduce
# List of some fibonacci numbers
fiboList = [0,1,1,2,3,5,8,13,21,34,55]
print("List of fibonacci numbers :",fiboList)
# using Lambda function to
# add elements of fibonacci list
listSum = reduce(lambda a,b:a+b,fiboList)
print("The sum of all elements is ",listSum)
Output
List of fibonacci numbers : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
The sum of all elements is 143
Python Lambda Function Programs »