1. LPU MCA Semester 1
  2. CAB106
  3. Unit 4

CAB106 · Unit 4: Abstraction, modules and packages

Lambda functions, iterators and generators

12 practice questions

Key points

  • lambda is a one-expression anonymous function
  • An iterator has __iter__ and __next__ and ends with StopIteration
  • Generators use yield and run lazily
  • A generator can be consumed only once

A lambda is an anonymous function made of a single expression, such as lambda x: x * 2. It is often passed to map, filter and sorted(key=...): filter keeps items that pass a test, map transforms each item, and the sort key decides the ordering.

An iterable can be looped over; an iterator is an object with __iter__ and __next__ that produces one item per next() call and raises StopIteration when finished. next(it, default) returns the default instead of raising. A class becomes an iterator by defining __iter__ (returning self) and __next__.

A generator is a function that uses yield. Calling it returns a generator object without running the body; each next() runs the code up to the next yield, so work is done lazily and memory stays small. yield from hands control to another iterable. A generator expression such as (x * x for x in range(3)) works the same way, and either kind can be consumed only once.

Exam trap: lambdas created in a loop capture the variable, not its value, so [lambda: i for i in range(3)] all return the last i.

Try two questions

Question 1 · Tier 2, Understand

What is the main advantage of a generator over building a full list of results?

  1. Values are produced one at a time, so memory use stays small
  2. The values are sorted automatically as they are produced
  3. The function can use return several times to send values
  4. The produced values become immutable and cannot be changed
Show the answer

A. Generators compute values lazily instead of storing them all.

Why not B: Generators do not sort anything.

Why not C: A generator uses yield for each value, and return ends it.

Why not D: Immutability is not a property of generators.

Question 2 · Tier 1, Recall

Which keyword creates a small anonymous function in Python?

  1. anonymous
  2. define
  3. function
  4. lambda
Show the answer

D. lambda builds a function without a name from a single expression.

Why not A: Python has no keyword called anonymous.

Why not B: Python has no keyword called define; def creates named functions.

Why not C: Python has no keyword called function.