Q:

Python program to find the sum of elements of a list using lambda function

belongs to collection: Python Lambda Function Programs

0

Lambda functions in Python are special functions available in python. They are anonymous functions i.e., without any function name. 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Map() Function and Lambda Expression in Python to ... >>
<< Python program to filter even values from list usi...