Thanks to visit codestin.com
Credit goes to www.tutorialsteacher.com

Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Lambda Functions and Anonymous Functions in Python

The def keyword is used to define a function in Python, as we have seen in the previous chapter. The lambda keyword is used to define anonymous functions in Python. Usually, such a function is meant for one-time use.

Syntax:
lambda [arguments] : expression

The lambda function can have zero or more arguments after the : symbol. When this function is called, the expression after : is executed.

Example: Lambda Function
square = lambda x : x * x

n = square(5)  #calling lambda function
Try it

Above, the lambda function starts with the lambda keyword followed by parameter x. An expression x * x after : returns the value of x * x to the caller. The whole lambda function lambda x : x * x is assigned to a variable square in order to call it like a named function. The variable name becomes the function name so that We can call it as a regular function, as shown below.

The above lambda function definition is the same as the following function:

def square(x):
    return x * x

The expression does not need to always return a value. The following lambda function does not return anything.

Example: Lambda Function
greet = lambda name: print('Hello ', name) 
greet('Steve')  #output: Hello Steve
Try it

The lambda function can have only one expression. Obviously, it cannot substitute a function whose body may have conditionals, loops, etc.

The following lambda function contains three parameters:

Example: Lambda Function
sum = lambda x, y, z : x + y + z 
n = sum(5, 10, 15) #returns 30
Try it

A lambda function can take any number of parameters by prefixing * before a parameter, as shown below:

Example: Multi-parameters Lambda Function
sum = lambda *x: x[0]+x[1]+x[2]+x[3]  
n = sum(5, 10, 15, 20) #returns 50
Try it

Parameterless Lambda Function

The following is an example of the parameterless lambda function.

Example: Parameterless Lambda Function
greet = lambda : print('Hello World!')
greet() #output: Hello World!
Try it

Anonymous Function

We can declare a lambda function and call it as an anonymous function, without assigning it to a variable.

Example: Anonymous Lambda Function
(lambda x: print(x*x))(5) #output 25
Try it

Above, lambda x: x*x defines an anonymous function and call it once by passing arguments in the parenthesis (lambda x: x*x)(5).

In Python, functions are the first-class citizens, which means that just as literals, functions can also be passed as arguments.

The lambda functions are useful when we want to give the function as one of the arguments to another function. We can pass the lambda function without assigning it to a variable, as an anonymous function as an argument to another function.

Example: Lambda Function as a Parameter
def dosomething(fn):
	print('Calling function argument:')
	fn()
	    
dosomething(lambda : print('Hello World')) # passing anonymous function

myfn = lambda : print('Hello World') 
dosomething(myfn) # passing lambda function
Try it

Above, the dosomething() function is defined with the fn parameter which is called as a function inside dosomething(). The dosomething(lambda : print('Hello World')) calls the dosomething() function with an anonymous lambda function as an argument.

Python has built-in functions that take other functions as arguments. The map(), filter() and reduce() functions are important functional programming tools. All of them take a function as their argument. The argument function can be a normal function or a lambda function.

Example: Pass Lambda Function to map()
sqrList = map(lambda x: print(x*x), [1, 2, 3, 4]) # passing anonymous function
next(sqrList)
next(sqrList)
next(sqrList)
next(sqrList)
next(sqrList) #error
Try it
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.