×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python reduce() with Lambda Function

By IncludeHelp Last updated : December 08, 2024

Python reduce() with Lambda Function

The reduce() function applies on each element of an iterable collection and returns the reduced (based on applied calculation through the function) value.

The lambda function is an anonymous function - that means the function which does not have any name.

Implementing reduce() with lambda function

Give a list of numbers and we have to find their sum using lambda and reduce() function.

Approach 1: Using normal way

# function to find sum of the elements
def add(data):
    s=0
    for n in data:
        s=s+n
    return s

# list of the values 
fibo=[0,1,1,2,3,5,8,13,21,34,55]
print("Orignal List  :",fibo)

# function call
s=add(fibo)
print("Sum = ",s)

Output

Orignal List  : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Sum =  143

Approach 2: Using reduce() with lambda

from functools import reduce

def add(data):
    s=0
    for n in data:
        s=s+n
    return s

# list of integers	
fibo=[0,1,1,2,3,5,8,13,21,34,55]
print("Orignal List  :",fibo)

# using reduce and lambda
s=reduce(lambda a,b:a+b,fibo)
print("Sum = ",s)

Output

Orignal List  : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Sum =  143

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.