Home Tutorials Python Tutorial Lambda Functions
Lambda Functions

Lambda Functions


Definition: A lambda function is a small, anonymous (unnamed) function in Python. Unlike standard functions defined with the def keyword, lambda functions are written in a single line and can only contain a single expression.

Why: Lambda functions are used when you need a quick, temporary function for a short period, often passed as an argument to higher-order functions like map(), filter(), or sorted().

Syntax

lambda arguments: expression

Example

# A lambda function that calculates the square of a number
square = lambda x: x * x

print(square(5))  # Output: 25

Explanation

  • The lambda Keyword: This tells Python that you are creating an anonymous function on the fly.
  • Arguments: x represents the input variable passed into the function, placed before the colon.
  • Expression: x * x is the operation performed on the input. Lambda functions automatically evaluate and return this single expression without needing an explicit return keyword.
  • Usage: In the example, the anonymous function is assigned to the variable square so it can be called like a regular function.

Key Notes

  • Lambda functions can take any number of arguments, but they can only ever have **one expression** (e.g., lambda a, b: a + b).
  • They cannot contain complex logic like loops, multiple statements, or try/except blocks.
  • While convenient for quick tasks, standard functions with def are preferred for complex, multi-line code to ensure readability.
Example

🏋️ Test Yourself With Exercises

Take our quiz on Lambda Functions to test your knowledge.

Exercise »