• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

Lambda Functions in Python with example | filter(), map(), reduce() in Lambda

  • December 18, 2021
  • CODE OF GEEKS
  • 0

Lambda function is a special one-liner function defined to perform a particular task. Since, lambda functions are not provided with any function name, hence are also as Anonymous Function.

Unlike normal functions, lambda functions are not defined using def keyword rather they are defined with lambda keyword in Python.

Syntax

lambda parameter_list : expression

In the above syntax, keyword lambda denotes that above function is a lambda function.

To see the difference between normal function and lambda function, let’s use one problem statement.



Program : To print cube of a number using normal function

def findcube(a):
    return a**3 
print(findcube(3))

O/P : 27



Here, we have defined a lambda function to evaluate the cube of a number ‘n’, ‘f’ is basically a function name to which this lambda expression has been assigned.

Lambda function can contain only one expression and upon evaluating the expression they implicitly return the result. This is the reason why lambda functions in Python does not use return statement.

Let’s check out a program to print the product of two integers.

Program : To print the sum of two integers.

f = lambda num1, num2: num1 + num2 # our lambda function
print(f(10,20)) # calling our lambda function with num1 = 10, num2 = 20

O/P : 30

Extra Gyan !

We can use lambda function inside a normal function as well.



Using lambda function with built-in functions

Using lambda with filter() function

As the name itself suggests that, filter() function is used to filter out some elements of a given sequence depending on the result. Though, we can pass normal functions to filter function as well, passing a lambda function to filter() is considered more elegant.

Syntax

filter(function, sequence)

Here, sequence may denote any of list, tuple, dictionary, or set.

Program : To filter out the odd numbers from a given list using lambda function.

list_of_integers = [23, 42, 12, 14, 15, 25, 20]
result = list(filter(lambda n: (n%2==1), list_of_integers))
print(result)

O/P : [23, 15, 25]

In line-2, we have used filter() function to keep note of all the odd integers in the list. We have passed two parameters to filter() function – first one is the lambda itself, that evaluates odd-checker logic for each element of the sequence, and second one is the list itself.

Extra Gyan !

Results obtained from filter() function needs to be explicitly type-casted.



Using lambda with map() function

Working of map() function is same as that of filter() function, however it acts on each element of the given sequence and modifies it.

Syntax

map(function, sequence)

Here, sequence may denote any of list, tuple, dictionary, or set, function is used to modify the existing elements of a sequence which can be stored to other sequence as well.

Program : To square each elements of the given list using lambda function

lst = [2, 4, 8, 10, 20]
res = list(map(lambda x: x**2, lst))
print(res)

O/P : [4, 16, 64, 100, 400]

In the above code, we have lst as our list(sequence) served to lambda function to do the operation. If result is not type-casted, then map object will be returned by default. One thing to note is that we can use map() function on two or more lists(or any other) if they are of same size.



Using lambda with reduce() function

reduce() function provides a single value result after processing elements (one by one) of the sequence according to the function specified.

Syntax

reduce(function, sequence)

Here, sequence may denote any of list, tuple, dictionary, or set, function is used to modify the existing elements of a sequence which can be stored to other sequence as well.

reduce() function belongs to functools module in Python, hence needs to be imported.

from functools import *

Program : To find the sum of elements of the given list using lambda function

from functools import *
lst = [2, 4, 8, 10, 20]
res = reduce(lambda x, y: x + y, lst)
print(res)

O/P : 44

In the above code, we have lst as our list(sequence) served to lambda function to do the operation.

Here’s, how it computes :

-> 2 + 4 = 6
-> 6 + 8 = 14
-> 14 + 10 = 24
-> 24 + 20 = 44

So, that’s all about Lambda Function in Python.





Tags: lambda function pythonlambda function python map filter reduce functionlambda function with filter functionlambda functions in python
  • Previous Function Decorator in Python with examples
  • Next Recursion in Python with examples | Types of Recursion

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.