1.2.32Introduction to Programming (Python)

Lambda functions — anonymous, used with map - filter

1,822 words8 min readdifficulty · medium3 backlinks

WHAT is a lambda?

So these two are the same function, just born differently:

def square(x):
    return x * x
 
square = lambda x: x * x      # identical behaviour

HOW map and filter use it

Both take (a function, an iterable) and return a lazy iterator (so wrap in list(...) to see results).

Figure — Lambda functions — anonymous, used with map - filter

DERIVATION — building map/filter from scratch

WHY do this? If you can rebuild them, you own them. They are just loops in disguise.

def my_map(f, it):
    result = []
    for x in it:
        result.append(f(x))   # transform every element
    return result
 
def my_filter(f, it):
    result = []
    for x in it:
        if f(x):              # keep only when predicate true
            result.append(x)
    return result

Worked examples


Common mistakes (Steel-manned)


Active recall

Recall Quick self-test (hide answers first!)
  1. What does a lambda return, and how? → The value of its single expression, automatically.
  2. list(map(lambda x: x+1, [0,9]))[1, 10]
  3. list(filter(lambda x: x>2, [1,2,3,4]))[3, 4]
  4. Why wrap map in list()? → It returns a lazy, one-pass iterator.
  5. Can a lambda contain a for loop? → No — single expression only.

Flashcards

What is a lambda function?
An anonymous (unnamed) function written inline as lambda args: expression; the expression's value is auto-returned.
How does a lambda return a value?
Implicitly — the single expression IS the return value; using return is a SyntaxError.
What does map(f, it) do?
Applies f to every element of it, yielding f(x) for each (lazy iterator).
What does filter(f, it) do?
Yields each x from it only when f(x) is truthy (a predicate-based selector).
Why must you often wrap map/filter in list()?
They return lazy iterators that compute on demand and exhaust after one pass.
list(map(lambda x: x*2, [1,2,3])) equals?
[2, 4, 6]
list(filter(lambda x: x%2==0, [1,2,3,4])) equals?
[2, 4]
Can a lambda hold statements like loops or assignments?
No — only a single expression (ternary a if c else b is allowed).
What does sorted(data, key=lambda p: p[1]) do?
Sorts data comparing by each item's second element.
What does filter(lambda x: x, items) return?
Only the truthy items (drops 0, '', None, [], False).

Recall Feynman: explain to a 12-year-old

Imagine a vending machine of helpers. Usually you build a helper, give it a name, and call it later. But sometimes you just need a one-time helper — like "double this number" — and naming it is a waste. A lambda is a sticky-note helper: you write the rule right where you hand it over. map is a worker who takes your sticky-note rule and does it to every item in a basket. filter is a bouncer who uses your rule to keep the items that pass and toss the rest. Tiny rule, big jobs.

Connections

  • Functions and def — lambda is the anonymous cousin of a named def.
  • First-class functions — why functions can be passed as arguments at all.
  • List comprehensions — often a more readable replacement: [x*2 for x in nums].
  • Iterators and lazy evaluation — why map/filter need list().
  • sorted and key functions — lambdas as sort keys.
  • Higher-order functions — functions that take/return other functions.

Concept Map

is

body is

auto-returned

enables passing

supplied to

supplied to

transforms every element

selects truthy elements

materialise with

rebuilt as

rebuilt as

Lambda function

Anonymous no name

Single expression

Functions first-class objects

map f it

filter f it

Lazy iterator

Wrap in list

Just loops in disguise

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, lambda ek chhota sa function hai jiska koi naam nahi hota — isliye usse "anonymous function" kehte hain. Jab tumhe ek bahut hi simple kaam karne wala function chahiye, jaise "number ko double kar do" ya "even hai ki nahi check karo", tab pura def likhne ki zaroorat nahi. Bas wahin inline likh do: lambda x: x*2. Yaad rakho — lambda mein return nahi likhte; jo expression likha hai, uski value khud return ho jaati hai.

Ab map aur filter ki baat. map(f, list) ka matlab — har element par function f lagao aur naya result do. Yani transform kar do sabko. filter(f, list) ka matlab — sirf wahi elements rakho jinpe f(x) True aata hai. Yani chhanti (selection) karo. Dono ke saath lambda mast jodi banati hai, kyunki yeh tools ko ek function chahiye hota hai, aur lambda turant wahin de deta hai.

Ek important baat jo students bhool jaate hain: Python 3 mein map/filter seedha list nahi dete, woh ek lazy iterator dete hain. Isliye result dekhne ke liye list(...) mein wrap karna padta hai. Aur yeh iterator ek hi baar chalti hai — dobara list() karoge to khaali aayega.

Lambda ke andar if/else to ek hi line wala (ternary) chalega — lambda x: 'even' if x%2==0 else 'odd' — lekin loop ya assignment nahi. Agar logic bada ho jaaye, to sidha named def use karo, padhne mein aasaan rehta hai. 80/20 rule: bas itna pakka kar lo — lambda = chhota inline function, map = sab par lagao, filter = sirf truthy rakho — aur tum 80% kaam aaram se kar loge.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections