Placement Prep

Lambda Functions in Python: Syntax, map, filter, and Pitfalls

Learn Python lambda syntax, how to use it with map(), filter(), and sorted(), when to prefer def, and the late-binding pitfall that catches most beginners.

By FACE Prep Team 5 min read
python lambda anonymous-functions map-filter placement-prep functional-programming beginners

A Python lambda is a one-line anonymous function defined with the lambda keyword, and the single-expression restriction is its most important characteristic to understand.

Lambda Syntax at a Glance

The syntax has three parts:

lambda <arguments> : <expression>
  • arguments — zero or more comma-separated parameter names, the same as a def function.
  • expression — a single expression whose value is returned implicitly. No return keyword. No assignments. No multiple statements.

Here is the same logic written as def and as lambda:

# Traditional def
def square(a):
    return a * a

result = square(6)
print(result)   # 36

# Lambda equivalent
f = lambda a: a * a

result = f(6)
print(result)   # 36

Both produce 36. The lambda version assigns the function object to f and calls it immediately. In practice, assigning a lambda to a variable like this is unusual. If you need a reusable named function, write def. Lambdas earn their place when passed inline as arguments to higher-order functions.

The restriction to a single expression is deliberate. The Python language reference for lambda expressions states that the body is an expression, not a statement block, which means the if/else ternary form is allowed (x if condition else y) but if as a statement is not.

Lambda with map()

map(function, iterable) applies a function to every item in an iterable and returns a map object. Wrapping it in list() produces a list of results.

Without lambda:

def double(a):
    return a * 2

numbers = [1, 2, 3, 4, 5]
result = list(map(double, numbers))
print(result)   # [2, 4, 6, 8, 10]

With lambda:

numbers = [1, 2, 3, 4, 5]
result = list(map(lambda a: a * 2, numbers))
print(result)   # [2, 4, 6, 8, 10]

The lambda replaces the named double function entirely. This is the idiomatic use: the function is so small and so specific to this one call that naming it adds noise.

A second example with strings:

words = ["face prep", "python", "lambda"]
lengths = list(map(lambda w: len(w), words))
print(lengths)  # [9, 6, 6]

Note: map(len, words) does the same thing with even less syntax; len is already a function object. The lambda is only necessary when the operation is not already a named function. You can also chain map and filter together: pass the output of filter() directly into map() to first narrow a list, then transform each remaining item.

Lambda with filter()

filter(function, iterable) returns only the items for which the function returns True. The pattern with lambda:

numbers = [12, 5, 18, 22, 97, 44]
evens = list(filter(lambda a: a % 2 == 0, numbers))
print(evens)    # [12, 18, 22, 44]

The lambda lambda a: a % 2 == 0 evaluates to True for even numbers and False for odd ones. filter() keeps the True cases.

Odd numbers instead:

odds = list(filter(lambda a: a % 2 != 0, numbers))
print(odds)     # [5, 97]

Filter with a string condition:

names = ["Arun", "Priya", "Raj", "Meena", "Jo"]
long_names = list(filter(lambda name: len(name) > 3, names))
print(long_names)   # ['Arun', 'Priya', 'Meena']

The condition len(name) > 3 keeps names with more than three characters. This pattern appears often in placement coding rounds where you must filter a dataset by one criterion before passing it to the next processing step.

For practice programs that use similar list-manipulation patterns, see the Python basic programs collection.

Lambda with sorted() and key=

sorted() has a key parameter that accepts a function. It calls that function on each element and sorts by the return value. The Python built-in functions reference for sorted() documents this parameter in detail.

Sort a list of tuples by the second element:

pairs = [(1, 3), (4, 1), (2, 5), (3, 2)]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs)     # [(4, 1), (3, 2), (1, 3), (2, 5)]

Sort strings by length instead of alphabetically:

words = ["banana", "fig", "apple", "kiwi"]
by_length = sorted(words, key=lambda w: len(w))
print(by_length)        # ['fig', 'kiwi', 'apple', 'banana']

Sort in reverse (longest first):

by_length_desc = sorted(words, key=lambda w: len(w), reverse=True)
print(by_length_desc)   # ['banana', 'apple', 'kiwi', 'fig']

The key=lambda pattern is one of the most common placements for lambda in real Python code. For a related program that sorts strings character-by-character, see sorting a string in alphabetical order.

When to Use def Instead

Readability test

If naming the function makes the intent clearer, use def. Compare:

# Lambda: intent buried in one line
result = sorted(students, key=lambda s: (s['cgpa'], s['name']))

# def: intent named explicitly
def sort_key(s):
    return (s['cgpa'], s['name'])

result = sorted(students, key=sort_key)

Both are correct. In a short script, the lambda is fine. In a module others will read, naming the key function aids comprehension. If you find yourself reading a lambda more than once to understand it, that is a reliable signal to switch to def.

Multi-expression needs

Lambda handles one expression. The moment you need to compute an intermediate value, assign a result, or write a condition that does not fit in a ternary, switch to def. As a concrete example, if you want to apply two transformations in sequence, a lambda forces you to nest the calls, which hurts clarity:

# Nesting is harder to read
process = lambda x: str(x * 2).strip()

# def makes the steps explicit
def process(x):
    doubled = x * 2
    return str(doubled).strip()

The def version is longer but easier to modify and easier to test individually.

Debugging lambda tracebacks

When a lambda raises an error, the traceback shows <lambda> as the function name. A def function shows its actual name, which makes error messages faster to act on. In a placement coding interview, a clear traceback can save time you do not have.

Late-binding closure pitfall in loops

This is the most common lambda mistake in placement coding rounds:

# Broken: all functions see the final value of i
funcs = [lambda x: x * i for i in range(4)]
print(funcs[0](2))  # Expected 0. Actual: 6
print(funcs[3](2))  # Expected 6. Actual: 6

The lambda closes over the variable i by reference, not by value. When the loop finishes, i is 3, so every function in the list multiplies by 3.

Fix: capture the current value using a default argument:

# Fixed: each function captures its own i_val
funcs = [lambda x, i_val=i: x * i_val for i in range(4)]
print(funcs[0](2))  # 0
print(funcs[1](2))  # 2
print(funcs[2](2))  # 4
print(funcs[3](2))  # 6

The i_val=i default argument is evaluated at definition time, not at call time. This freezes the current value of i into each function independently.


The key=lambda pattern in sorted() is the gateway to processing structured data in Python, covering sorting student records by score, filtering API response lists by a field, and mapping over a sequence of objects. Those patterns scale directly into LLM-powered data pipelines. TinkerLLM is a Python-friendly environment to prototype that kind of pipeline for ₹299, a practical next step once sorting and filtering exercises feel familiar.

Primary sources

Frequently asked questions

Can a lambda function have multiple expressions?

No. Python lambda is restricted to a single expression. If you need multiple statements or a return with conditional logic across lines, use def instead.

Is a lambda function faster than a def function in Python?

Not measurably. CPython compiles both to bytecode at similar speed. The choice between lambda and def is about readability and structure, not performance.

What is the difference between lambda and def in Python?

A def function has a name, supports docstrings, and can contain multiple statements. A lambda is anonymous, restricted to one expression, and defined inline.

Can I use lambda with reduce()?

Yes. Import reduce from functools and write functools.reduce(lambda acc, x: acc + x, numbers) to sum a list. The same pattern works for any associative operation.

Why does key=lambda appear in sorted() calls?

The key parameter tells sorted() what value to compare. key=lambda x: x[1] sorts a list of tuples by the second element without writing a separate named function.

Why should I avoid lambda inside a for loop?

Python closures capture variable references, not values. A lambda defined in a loop body closes over the loop variable by reference, so all copies see the final value of that variable. Use a default argument to capture the current value.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF