Sometimes you need a tiny function only once, for example to tell sorted() how to order items. Defining it with def would be clumsy, so Python offers lambda functions.
Lambda functions
A lambda can take any number of parameters, but its body is a single expression: no statements such as assignments, loops or return.
The result of the expression is returned automatically.
lambda x: x * x is equivalent to def f(x): return x * x, except that it has no name.
PEP 8 recommends def instead of assigning a lambda to a name (cube = lambda x: x ** 3 works, but def cube(x): is clearer). Lambdas are best used directly as arguments.
map() and filter()
Function
What it does
Example
Result (as a list)
map(func, iterable, ...)
Applies func to every item (or to items taken in parallel from several iterables)
map(lambda x: x ** 3, [1, 2, 3])
[1, 8, 27]
filter(func, iterable)
Keeps the items for which func returns a true value
filter(lambda x: x % 2 == 0, [1, 2, 3, 4])
[2, 4]
Both return iterators (lazy objects that produce items on demand), so wrap them in list() to see or reuse the results.
The same results can be written as list comprehensions, which many Python programmers find clearer: [x ** 3 for x in nums] and [ch for ch in letters if ch in "aeiou"].
Key takeaways
lambda args: expression is an anonymous one-expression function.
map transforms every item; filter keeps items that pass a test.
Both return iterators; use list() to collect results.
Lambdas are best as arguments, for example key= in sorted().
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Using sorted() and a lambda, sort a list of (name, marks) tuples by marks in descending order, and give the result for [("Asha", 72), ("Ravi", 88), ("Neha", 65)].
Show worked answer
sorted(results, key=lambda r: r[1], reverse=True). The key function picks the marks (item 1 of each tuple) for comparison, and reverse=True puts the highest first. Result: [("Ravi", 88), ("Asha", 72), ("Neha", 65)].
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/functions-and-file-handling-in-python/lambda-functions-map-and-filter/ to read this page.