Lambda Functions

Published by Brayan K

Sometimes you need a function for just a moment — a tiny rule that says "sort by this" or "double that" — and writing a full def feels heavy. A lambda is a one-line, throwaway function built exactly for these passing needs.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A lambda is a function written as an expression

A lambda is the word lambda, the parameters, a colon and one expression. Calling it returns the value of that expression, with no return written:

def double(x):
    return x * 2

double_too = lambda x: x * 2

print(double(5), double_too(5))
print(type(double_too))
print(double.__name__, double_too.__name__)

# ✅ Expected output:
# 10 10
# <class 'function'>
# double <lambda>

A lambda makes the same kind of function a def does, but without a name of its own: its __name__ is <lambda>, even when it's stored in a variable, and that's also what a traceback calls it when something goes wrong inside it. That's why PEP 8, Python's style guide, says to write a def rather than assign a lambda to a name as double_too does here. A lambda is for passing a small function straight into a call, which is what the rest of this lesson does. Like a def, it can take several parameters, as in lambda a, b: a + b, or none, as in lambda: 0.

One expression, nothing else

The expression already is the return value, so writing return stops the program before it starts:

square = lambda n: return n * n

# ✅ Expected error:
# SyntaxError: invalid syntax

The same goes for any statement: an if block or a loop is a SyntaxError too, and an assignment such as lambda n: total = n stops with SyntaxError: cannot assign to lambda. A conditional expression is allowed, because it is an expression:

parity = lambda n: "even" if n % 2 == 0 else "odd"
print(parity(4), parity(7))

# ✅ Expected output:
# even odd

Naming a lambda is fine for trying one out, as here. Conditional Expressions (Ternary) covers the a if condition else b form.

key= decides what gets compared

sorted(), max() and min() take a key: a function they call once on each item, ordering the items by what it returns. What you get back are the original items:

words = ["banana", "kiwi", "apple", "Fig"]
print(sorted(words))
print(sorted(words, key=len))
print(sorted(words, key=lambda w: w.lower()))
print(max(words, key=len))

# ✅ Expected output:
# ['Fig', 'apple', 'banana', 'kiwi']
# ['Fig', 'kiwi', 'apple', 'banana']
# ['apple', 'banana', 'Fig', 'kiwi']
# banana

Without a key, capitals come first, as Lists and Collections showed. len is already a function, so it's passed by name. A lambda is for when no function exists yet, like "the word in lower case" (.lower() gives a lower-case copy of a string, one of the String Methods). Passing the function is the point, so parentheses after len break it:

words = ["banana", "kiwi"]
print(sorted(words, key=len()))

# ✅ Expected error:
# TypeError: len() takes exactly one argument (0 given)

len() runs right there, with nothing to measure, before sorted() starts: the same difference as between greet and greet() in Functions. And the key has to be named, because key is keyword-only, like the parameters after *args:

words = ["banana", "kiwi"]
print(sorted(words, lambda w: len(w)))

# ✅ Expected error:
# TypeError: sorted expected 1 argument, got 2

max() and min() of an empty list stop with a ValueError, whose wording differs between Python versions. Give them default= and they return that instead:

entries = []
print(max(entries, key=len, default="nothing yet"))

# ✅ Expected output:
# nothing yet

Sorting records by one of their parts

The commonest lambda picks one part of each item. Here each item is a pair, a tuple like the ones a function returns with return a, b, and s[1] is the score:

scores = [("Ada", 88), ("Ben", 72), ("Cleo", 95), ("Dev", 88)]
print(sorted(scores, key=lambda s: s[1], reverse=True))
print(max(scores, key=lambda s: s[1]))
print(min(scores, key=lambda s: s[1])[0])

# ✅ Expected output:
# [('Cleo', 95), ('Ada', 88), ('Dev', 88), ('Ben', 72)]
# ('Cleo', 95)
# Ben

max() returns the whole pair, not 95, so [0] after min() picks out the name. Ada and Dev tie on 88 and stay in their original order: Python's sort keeps equal items as they were, which Sorting with sorted() & key uses to sort by two things at once. A dictionary's .items() gives pairs like these, so the same lambda finds the key with the largest value:

counts = {"ana": 3, "ben": 1, "cara": 2}
print(max(counts.items(), key=lambda item: item[1]))
print(sorted(counts.items(), key=lambda item: item[1], reverse=True))

# ✅ Expected output:
# ('ana', 3)
# [('ana', 3), ('cara', 2), ('ben', 1)]

The operator Module has itemgetter(1), a ready-made function that does what lambda s: s[1] does.

map() and filter()

map() calls a function on every item, and filter() keeps the items the function returns a true value for: True, or anything else an if would count as true, such as 1. Neither gives you a list:

nums = [1, 2, 3, 4, 5, 6]
doubled = map(lambda n: n * 2, nums)
print(type(doubled))
print(list(doubled))
print(list(doubled))

print(list(filter(lambda n: n % 2 == 0, nums)))
print(list(map(str, [1, 2, 3])))

# ✅ Expected output:
# <class 'map'>
# [2, 4, 6, 8, 10, 12]
# []
# [2, 4, 6]
# ['1', '2', '3']

map() and filter() return an iterator, which hands over its values one at a time, when asked, and only once. The first list(doubled) took all of them, so the second is empty. Wrap the call in list() once and keep the list. The last line passes a named function, str, which turns each number into text.

A comprehension does both jobs and often reads better: [n * 2 for n in nums] and [n for n in nums if n % 2 == 0], which Comprehensions covers. Higher-Order Functions & Function Factories goes further with functions that take and return functions, and functools: lru_cache, partial, reduce adds reduce(), which combines all the items into one value.

When a def is clearer

A lambda has no name, no docstring and room for one expression. Once a key needs any of those, or you'd write the same lambda twice, write a def and pass it by name, just as key=len passes len:

def by_score(entry):
    """Sort key: the score in a (name, score) pair."""
    return entry[1]

scores = [("Ada", 88), ("Ben", 72), ("Cleo", 95)]
print(sorted(scores, key=by_score))
print(max(scores, key=by_score))

# ✅ Expected output:
# [('Ben', 72), ('Ada', 88), ('Cleo', 95)]
# ('Cleo', 95)

One more trap: a lambda looks up the names it uses when it's called, not when it's made. Lambdas made inside a loop that use the loop variable all see its last value; Closures & Lexical Scope in Real Projects shows why, and the fix.

Practice: products by price

Fill the three blanks with the values in the hint lines, in order: find the cheapest product, then list them all from the most expensive down.

products = [
    {"name": "Mouse", "price": 25},
    {"name": "Monitor", "price": 180},
    {"name": "Cable", "price": 8},
]
cheapest = min(products, ___=lambda p: p["price"])
print(cheapest["name"])

by_price = sorted(products, key=lambda p: p[___], reverse=___)
for p in by_price:
    print(p["name"], p["price"])

# 👉 replace ___ with key
# 👉 replace ___ with "price"
# 👉 replace ___ with True

# ✅ Expected output:
# Cable
# Monitor 180
# Mouse 25
# Cable 8

On your own: files by size

files holds (name, size in KB) pairs: [("report.pdf", 240), ("photo.jpg", 1800), ("notes.txt", 12), ("video.mp4", 52000)]. With lambdas, print each file and its size from smallest to largest, then the name of the largest file, then a list of the names of the files under 1000 KB, which are report.pdf and notes.txt. Then compare with this solution:

files = [("report.pdf", 240), ("photo.jpg", 1800), ("notes.txt", 12), ("video.mp4", 52000)]

for name, size in sorted(files, key=lambda f: f[1]):
    print(name, size)

print("Largest:", max(files, key=lambda f: f[1])[0])

small = []
for name, size in filter(lambda f: f[1] < 1000, files):
    small.append(name)
print("Small:", small)

# ✅ Expected output:
# notes.txt 12
# report.pdf 240
# photo.jpg 1800
# video.mp4 52000
# Largest: video.mp4
# Small: ['report.pdf', 'notes.txt']

A for loop can go through what filter() returns directly, without list(), because a loop asks the iterator for its values one by one.

Practice quiz

square = lambda n: n * n. What does square(4) return?

  • 8
  • 16
  • None
  • An error

Answer: 16. A lambda returns the value of its expression, here 4 * 4.

Which def does the same as lambda x: x * 2?

  • def f(x): print(x * 2)
  • def f(x): x * 2
  • def f(x): return x * 2
  • def f(): return x * 2

Answer: def f(x): return x * 2. A lambda returns its expression, so the def needs return. Without it the def returns None.

What does sorted(["kiwi", "fig", "apple"], key=len) return?

  • ['fig', 'kiwi', 'apple']
  • ['apple', 'fig', 'kiwi']
  • [3, 4, 5]
  • ['apple', 'kiwi', 'fig']

Answer: ['fig', 'kiwi', 'apple']. The words are ordered by their lengths, 3, 4 and 5, and the list holds the words themselves.

What happens with sorted(words, key=len())?

  • It sorts by length
  • It sorts alphabetically
  • It returns None
  • It stops with TypeError: len() takes exactly one argument (0 given)

Answer: It stops with TypeError: len() takes exactly one argument (0 given). The parentheses call len at once, with nothing to measure. key needs the function itself: key=len.

scores = [("Ada", 88), ("Ben", 95)]. What does max(scores, key=lambda s: s[1]) return?

  • 95
  • ('Ben', 95)
  • 'Ben'
  • 1

Answer: ('Ben', 95). max compares the scores but returns the whole item that has the largest one.

Which of these is a SyntaxError?

  • lambda n: n + 1
  • lambda: 42
  • lambda n: return n + 1
  • lambda a, b: a * b

Answer: lambda n: return n + 1. A lambda's body is one expression, which is returned without writing return.

doubled = map(lambda n: n * 2, [1, 2]). What does print(list(doubled), list(doubled)) print?

  • [2, 4] []
  • [2, 4] [2, 4]
  • [] []
  • An error

Answer: [2, 4] []. map gives an iterator, and the first list() uses up its values.

f = lambda: 0. What does print(f.__name__) print?

  • f
  • lambda
  • 0
  • <lambda>

Answer: <lambda>. A lambda has no name of its own, even when it's stored in a variable.

Continue this course

Frequently asked questions

Why is it called lambda?

The name comes from the lambda calculus, a mathematical way of describing functions that Alonzo Church developed in the 1930s and wrote with the Greek letter λ. Several programming languages borrowed the word for functions written without a name.

Is a lambda faster than a def?

No. Both make the same kind of function object, and calling one costs the same as calling the other. Choose between them by which reads more clearly.

Related lessons