Wednesday, July 30, 2025

Python Lambda Functions With Examples

Python lambda function is a function without any name (an anonymous function) which is created using lambda keyword. Syntax of lambda function in Python is as given below.

lambda argument(s):expression

Any lambda function starts with the keyword lambda.

  • argument(s)- Parameters passed to the lambda function. Number of parameters can be 0…n.
  • expression- Logic of the lambda function.

Lambda function examples

Here is a simple example of lambda function that squares the passed number.

lambda num : num**2

Here num is the argument which is on the left side of the colon (:) and right side of it is the logic that will be executed when this lambda function is called.

The above lambda function is equivalent to the following regular function.

def square(num):
    return num ** 2

In order to execute this lambda function you can assign it to a variable. That variable essentially holds the lambda function so it can be called like a regular function using this variable.

square = lambda num : num**2
print(square(9)) #81

Another way is to immediately invoke it-

(lambda num : num**2)(9)

Some other examples of lambda functions.

1. With out any argument

msg = lambda :print("Hello")

msg() # Hello

2. Lambda function with one argument.

msg = lambda m : print(m)

msg("Hello there") # Hello there

3. Lambda function with two arguments. Gets the max of two numbers.

max = lambda x, y : x if x > y else y

print(max(17, 14)) #17

When to use lambda functions

  1. For simple operations- When logic is simple enough to be expressed in a single line and a function is needed for one time use, lambda function is a more concise and readable alternative to regular function.
  2. Used as argument for higher order functions- Higher order functions like map, filter, sorted which need another function as argument can use lambda function as that argument. That allows for the inline implementation of the function logic needed as argument in these higher order functions.

That's all for this topic Python Lambda Functions With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Python Generator, Generator Expression, Yield Statement
  3. Python Functions: Returning Multiple Values
  4. Global Keyword in Python With Examples
  5. Namespace And Variable Scope in Python

You may also like-

  1. Python String split() Method
  2. Convert String to int in Python
  3. Magic Methods in Python With Examples
  4. List Comprehension in Python With Examples
  5. Lambda Expressions in Java 8
  6. Java Map putIfAbsent() With Examples
  7. Spring Setter Based Dependency Injection
  8. Data Loader in React Router