Lambda Functions
Introduction to Python
Getting Started
Comments
Variables
Data Types
Type Casting
Input and Output
Operators
Strings
Booleans
Conditional Statements
While Loop
For Loop
Loop Control Statements
Lists
Tuples
Sets
Dictionaries
Functions
Function Arguments and Return Values
Variable Scope
Recursion
Lambda Functions
Arrays and Python Lists
Modules
Dates and Math
String Formatting
File Handling
Try and Except
Classes and Objects
Inheritance
Iterators
JSON
RegEx
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
lambdaKeyword: This tells Python that you are creating an anonymous function on the fly. - Arguments:
xrepresents the input variable passed into the function, placed before the colon. - Expression:
x * xis the operation performed on the input. Lambda functions automatically evaluate and return this single expression without needing an explicitreturnkeyword. - Usage: In the example, the anonymous function is assigned to the variable
squareso 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/exceptblocks. - While convenient for quick tasks, standard functions with
defare preferred for complex, multi-line code to ensure readability.
Example
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on Lambda Functions to test your knowledge.
Exercise »