A lambda function is a small, anonymous function written in a single expression: lambda arguments: expression. Lambdas are handy for short operations you pass to other functions such as sorted(), map() and filter().
What You Will Learn
- Lambda syntax
- Lambdas with map, filter and reduce
- Sorting with a key function
- Conditional expressions in lambdas
- When to use def instead
Prerequisites
Syntax
square = lambda x: x * x
print(square(5))
add = lambda a, b: a + b
print(add(3, 4))
25 7
Explanation: A lambda returns the value of its expression automatically – no return keyword. It can take any number of arguments but only one expression.
map, filter and reduce
from functools import reduce
nums = [5, 2, 9, 1, 7]
print(list(map(lambda x: x * 2, nums))) # transform every item
print(list(filter(lambda x: x > 4, nums))) # keep items that pass a test
print(reduce(lambda a, b: a + b, nums)) # combine into one value
[10, 4, 18, 2, 14] [5, 9, 7] 24
Explanation: map applies the lambda to each item, filter keeps items where it returns True, and reduce repeatedly combines two values. List comprehensions such as [x * 2 for x in nums] are often clearer for map and filter.
Sorting with key=
students = [("Aman", 82), ("Riya", 91), ("Karan", 68)]
print(sorted(students, key=lambda s: s[1], reverse=True))
[('Riya', 91), ('Aman', 82), ('Karan', 68)]
Explanation: The key lambda tells sorted to compare the second item (marks) of each tuple. This is the most common real use of lambdas, also in pandas: df.sort_values(key=...) and df.apply(lambda row: ...).
Conditional Lambda
grade = lambda m: "Pass" if m >= 75 else "Fail"
print([grade(m) for _, m in students])
['Pass', 'Pass', 'Fail']
Lambda vs def
| Use lambda when… | Use def when… |
|---|---|
| The function is one short expression | It needs several statements |
| It is used once, inline (key=, map) | It is reused or needs a name |
| It needs a docstring, type hints or error handling |
square = lambda x: …) in real code – use def square(x): instead. We do it here only to demonstrate the syntax.Series
Python series: What is Python · Installation · Syntax · Variables · Operators · Decisions · Loops · Strings · Lists · Dictionary · Functions · Lambda · Modules · Files · Exceptions · OOP · Classes & Objects · Inheritance · Decorators · Generators · Virtual Environments
Interview Questions
Q: What is a lambda?
An anonymous single-expression function created with the lambda keyword.
Q: Can a lambda contain multiple statements?
No, only one expression.
Practice Exercises
- Sort a list of words by their length using a lambda.
- Use filter and a lambda to keep only even numbers from 1 to 20.
Summary
Lambdas are short anonymous functions, ideal as key functions and with map/filter/reduce. Use def for anything longer or reused.
Machine Learning Tutorials, Courses and Certifications