1.2.32 · D1Introduction to Programming (Python)

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

2,313 words11 min readBack to topic

Before you touch a single lambda, you need to be fluent with a handful of symbols and ideas the parent note assumes you already own. This page builds each one from zero, in the order that they depend on each other. Nothing here uses a symbol before it is drawn.


0 · What a "function" even is (the machine picture)

Figure 1 (below) — the machine picture: an input arrow enters the box, the rule runs, an output arrow leaves.

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

Look at Figure 1. The box is the machine. The orange arrow going in carries the argument 5; the plum arrow coming out carries the return value 25. In Python you build such a machine with def:

def square(x):     # x is the input arrow
    return x * x   # this is the output arrow
  • WHAT def square(x): does — it names a new machine square that expects one input, which it calls x.
  • WHY we need return — without it the machine produces nothing (None); return is the output chute.
  • This is the Functions and def idea. A lambda, coming later, is the same machine born without a name.

1 · The symbols inside the rule

The parent note writes rules like x * 2, x % 2 == 0, x * x. Let's earn each symbol.

Figure 2 (below) — why x % 2 is an even/odd detector: pair the items up and read the leftover.

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

Look at Figure 2. Split a pile of x items into pairs. If nothing is left over, the remainder is 0even. If one item dangles, the remainder is 1odd. So x % 2 == 0 is asking "did the pairs come out clean?" — the exact test used in the parent's even-number example.


2 · True, False, and "truthy" — the yes/no world

filter (which we define in §5) keeps items where the rule is truthy. So we must nail down what that word means.

Figure 3 (below) — every value drops into one of two bins: falsy (empty/nothing) or truthy (everything else).

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

Look at Figure 3. The rule is not a memorised blacklist — it is a general principle:

  • WHY this matters: in §5 you'll see filter(f, it) keeps x whenever bool(f(x)) is True. So the parent's idiom filter(lambda x: x, items) keeps every item that isn't zero-or-empty.

3 · Collections you can walk through: the iterable

The parent feeds lists like [1, 2, 3, 4] into map/filter. What is that, and why does the shape matter?

for x in [1, 2, 3]:   # colon ends the header; the indented body runs once per x
    print(x)          # x becomes 1, then 2, then 3
  • The square brackets [...] make a list; the round brackets (...) make a tuple (a fixed little group, like the pair (3, 'a') in example 4).
  • WHY map/filter demand an iterable — they are secretly for loops (the parent proves this by rebuilding them), and a for loop needs something to walk over.

4 · Indexing: reaching inside with p[1]

Example 4 uses key=lambda p: p[1]. That [1] is indexing, not a list.


5 · The two tools: what map and filter actually do

The parent hands rules to map and filter but never opens them up. Here is their exact behaviour.

You already have every symbol to read their true definition — they are just the for loops from §3:

def my_map(f, it):
    out = []
    for x in it:          # walk the iterable
        out.append(f(x))  # transform: store f(x)
    return out
 
def my_filter(f, it):
    out = []
    for x in it:
        if f(x):          # select: keep x only when f(x) is truthy
            out.append(x)
    return out
  • WHAT each does — map stores f(x) for every x; filter stores x only if f(x) is truthy.
  • WHY the truthiness of §2 mattered — it is exactly the if f(x): test in my_filter.

6 · Passing a function as a value — and finally, the lambda

Here is the keystone: map(f, it) takes a function f as its first argument.

def apply(f, x):   # f is a MACHINE handed in as a value
    return f(x)
 
apply(square, 5)   # -> 25   (square the machine, not square(5))
  • WHAT just happened — square (the machine itself) was passed in and then called inside.
  • WHY this unlocks lambdas — if a machine is just a value you pass, it's wasteful to def and name a one-time machine.

Now we can meet the star of the parent page directly:

Translate the machine picture of Figure 1 into a lambda, side by side:

def square(x):        # named machine
    return x * x
 
square = lambda x: x * x   # SAME machine, written in one line
 
add_one = lambda x: x + 1  # concrete tiny example
add_one(9)                 # -> 10
  • WHAT lambda x: x + 1 means — "input x, output x + 1", exactly the machine of Figure 1 with a different rule.
  • WHY no return — the single expression x + 1 is the output; a lambda has no room for statements.
  • How it plugs in — hand this tiny machine straight to the tools of §5: list(map(lambda x: x + 1, [0, 9])) gives [1, 10]. That inline lambda x: x + 1 is the entire pitch of the parent note.

Prerequisite map — how to read it

The diagram below is a dependency chart: an arrow A --> B means "you need A before B makes sense." Start at the top boxes (things that depend on nothing), follow arrows downward, and you arrive at the parent topic in the bottom box. If you can trace every arrow and explain its label, you are ready.

named with def

body uses

groups blocks

comparisons give

for loop walks

filter keeps truthy

pass rule inline

receive the rule

reach into tuples

transform rule

Function is a machine

Symbols star percent equalequal

Colon indent commas

True False truthy

Iterable you can walk

Indexing p at 1

Functions are values

map and filter

Lambda with map and filter

Read top-down: punctuation and the machine idea come first; the machine splits into "give it a name" (functions-as-values) and "what symbols live inside it". Booleans and iterables feed the two tools map/filter, and those tools plus first-class functions finally meet in the lambda.


Equipment checklist

What is a function, in one picture?
A machine: input goes in, the rule runs, an output comes back.
What does return do?
Sends a value out of the function as its output; without it you get None.
What does the colon : do in def f(x):?
Ends the header line and introduces the indented block that belongs to it.
How does Python know which lines form a block?
By indentation — lines pushed in by the same amount are one block.
What does 7 % 2 evaluate to, and why?
1 — it is the remainder after dividing 7 by 2.
How do you test if x is even?
x % 2 == 0 (the remainder after pairing is zero).
Difference between = and ==?
= stores a value into a name; == asks "are these equal?" and returns True/False.
State the general falsy rule.
A value is falsy when it is numeric zero, any empty container ('', [], (), {}, set(), range(0)), or None/False; everything else is truthy.
What is an iterable?
Anything you can walk through one item at a time with a for loop (list, tuple, string).
For p = (3, 'a'), what is p[1]?
'a' — indexing starts at 0, so position 1 is the second item.
What does map(f, it) return and do?
A lazy iterator that yields f(x) for every x in it (transforms every element).
What does filter(f, it) do?
Yields each x only when bool(f(x)) is True (selects the truthy ones).
Write the machine x -> x+1 as a lambda.
lambda x: x + 1 — the single expression is auto-returned.

Connections

  • Functions and def — the named machine a lambda is the anonymous version of.
  • First-class functions — why a function can be passed as an argument at all.
  • Higher-order functions — tools like map/filter that take a function.
  • Iterators and lazy evaluation — what map/filter return once fed an iterable.
  • sorted and key functions — where indexing p[1] becomes a sort key.
  • List comprehensions — an alternative that uses these same symbols.