Lambda Functions

Concepts covered: Lambda

A lambda expression builds a function object without a def statement and without a name. Writing lambda params: expression evaluates to a function. Calling that function binds the arguments to the parameters, evaluates the expression and returns the result. There is no return keyword: the single expression is the return value.

def engagement(post):
    return post[1] + post[2]

print(engagement(("p1", 340, 12)))
print((lambda post: post[1] + post[2])(("p1", 340, 12)))

Output:

352
352

Both calls print 352. The second line builds a function, calls it where it stands and discards it, which is legal and rarely useful. A lambda pays off when you hand it to code that calls it for you.

Where a lambda earns its place

Several built-ins take a function as an argument: the key of sorted, min and max, and the first argument of map and filter. functools.reduce, which you import before calling it, takes its folding function the same way. In those slots the function is used once, at the spot where it is written, and a def elsewhere would add a name the reader has to go and find.

posts = [("p1", 340), ("p2", 1205), ("p3", 87), ("p4", 1205)]

ranked = sorted(posts, key=lambda p: (-p[1], p[0]))
print(ranked)

top = max(posts, key=lambda p: p[1])
print(top)

popular = list(filter(lambda p: p[1] >= 300, posts))
print(popular)

labels = list(map(lambda p: f"{p[0]}:{p[1]}", posts))
print(labels)

Output:

[('p2', 1205), ('p4', 1205), ('p1', 340), ('p3', 87)]
('p2', 1205)
[('p1', 340), ('p2', 1205), ('p4', 1205)]
['p1:340', 'p2:1205', 'p3:87', 'p4:1205']

The tuple key (-p[1], p[0]) sorts by likes descending, then by id ascending, which breaks the tie between p2 and p4. Negating the number flips only that part of the order; reverse=True would flip the ids as well. max returns the first post it meets with the highest key, so p2 also wins that tie.

What fits in the body

The body is a single expression. A conditional expression, a function call, arithmetic and a comprehension are all expressions, so they fit. An assignment, a return, a loop, a try block or a second line are statements, and writing any of them inside a lambda is a SyntaxError.

Fits in a lambda
  • lambda n: "viral" if n > 1000 else "normal"
  • lambda p: p[1] * 2 + p[2]
  • lambda xs: [x for x in xs if x > 0]
  • lambda a, b=0, *rest: a + b + len(rest)
Needs a def
  • A variable assigned with = partway through
  • A for or while loop
  • A try and except around a risky step
  • A docstring explaining a business rule
  • Several steps that each deserve a name

Lambdas accept every parameter form a def does: defaults, *args, **kwargs and keyword-only parameters after a bare *. A lambda built inside a loop is a closure like any other, so it falls into the same late-binding trap, and a k=k default fixes it the same way.

When a def is the better choice

Every lambda carries the same __name__, '<lambda>', so a traceback raised inside one names no function and leaves you guessing which of a dozen lambdas failed. Binding a lambda to a variable with = keeps that anonymous name and saves nothing over a def; PEP 8, Python's style guide, says to write the def.

score = lambda p: p[1] / 1000

def score_def(p):
    return p[1] / 1000

print(score.__name__ == "score")
print(score_def.__name__)
print(score(("p2", 1205)) == score_def(("p2", 1205)))

Output:

False
score_def
True

What does this program print?

events = [("ana", 3), ("bo", 12), ("cy", 7)]
pick = sorted(events, key=lambda e: e[1] % 5)
print([name for name, _ in pick])

Keys computed from several fields

rows = [
    {"user": "ana", "likes": 340, "shares": 12},
    {"user": "bo", "likes": 300, "shares": 52},
    {"user": "cy", "likes": 1205, "shares": 0},
    {"user": "dee", "likes": 300, "shares": 52},
]

by_reach = sorted(rows, key=lambda r: (-(r["likes"] + r["shares"]), r["user"]))
print([r["user"] for r in by_reach])

reach = list(map(lambda r: (r["user"], r["likes"] + r["shares"]), rows))
print(reach)

Output:

['cy', 'ana', 'bo', 'dee']
[('ana', 352), ('bo', 352), ('cy', 1205), ('dee', 352)]

The key adds likes and shares inside the lambda and negates the sum, so the largest reach sorts first. The user name after it settles the 3-way tie at 352 in alphabetical order. sorted calls a key function once per item and compares the stored keys, so the addition runs 4 times here, never once per comparison. The map call reuses the same expression to turn each row into a (user, reach) pair.

About this lesson

This section is part of the Functional Programming: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.