Lesson 4.3: Lambda Functions (Anonymous Functions in Python)
Introduction:
Lambda functions are small, anonymous, one-line functions in Python. They are useful when you need a simple function for a short task and do not want to define a full function using def. Lambda functions help make your code concise and readable, especially when used with functions like map(), filter(), and reduce().
1. Syntax of Lambda Functions:
Example – Simple Lambda Function:
Output:
Explanation:
-
aandbare input arguments -
The expression
a + bis evaluated and returned -
No need to use
returnkeyword
2. Lambda with map():
-
map()applies a function to each item in a list or sequence.
Output:
3. Lambda with filter():
-
filter()filters elements based on a condition.
Output:
4. Lambda with reduce():
-
reduce()(fromfunctoolsmodule) applies a function cumulatively to items of a sequence.
Output:
Practical Tips:
-
Use lambda functions for simple tasks; avoid using them for complex logic
-
Ideal for short operations passed as arguments to other functions
-
Keep code readable and avoid overusing lambda in large programs
Learning Outcome of This Lesson:
-
Understand what lambda functions are and when to use them
-
Write concise one-line functions using
lambda -
Apply lambda functions with
map(),filter(), andreduce() -
Improve code efficiency for small, reusable operations
