MCS-201 · Unit 11

Functions and File Handling in Python

Section 6 of 8

Block 3 · Unit 11Functions and File Handling in Python10 min · Section 6 of 8

11.6Lambda Functions, map() and filter()

Covers IGNOU MCS-201 §11.7

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()

FunctionWhat it doesExampleResult (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 valuefilter(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 1 · multiple choice

What is (lambda x, y: x * y)(3, 4)?

Show answer

Answer: B. 12

The lambda is created and immediately called with 3 and 4, returning 3 × 4 = 12.

Question 2 · multiple choice

What does list(filter(lambda n: n > 2, [1, 3, 2, 5])) give?

Show answer

Answer: A. [3, 5]

filter keeps the items for which the test is true; it does not return the test results themselves (that would be map).

Question 3 · multiple choice

What does this program print?

Python · quiz_map.py
words = ["mca", "ignou", "py"]
print(list(map(len, words)), list(map(str.upper, words))[1])
Show answer

Answer: C. [3, 5, 2] IGNOU

Any function can be passed to map; the lengths are 3, 5 and 2, and item 1 of the upper-cased list is “IGNOU”.

Question 4 · multiple choice

Which is a valid lambda?

Show answer

Answer: D. lambda x, y=1: x + y

Lambdas can have default parameters, and their body must be a single expression without return or assignment.

Question 5 · multiple choice

What does print(map(abs, [-1])) display in Python 3?

Show answer

Answer: C. Something like <map object at 0x7f...>

map returns an iterator object; printing it shows the object, not its items.

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)].

↑ ↓ move↵ openTab switch type