Python
Coding Best Practices
Lambda Expressions
Software Development
Programming Tips

E731 do not assign a lambda expression, use a def

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

E731 is a style warning from Python linters such as pycodestyle and flake8. It appears when you assign a lambda to a name, because once a function has a stable name, a normal def is usually clearer, easier to debug, and more consistent with Python style.

What Triggers E731

The warning appears for code like this:

python
square = lambda x: x * x

That code works, but it is discouraged because the function is no longer anonymous in practice. You gave it a name, so the more readable form is:

python
def square(x):
    return x * x

The behavior is similar, but the def version communicates intent more directly.

Why Linters Prefer def

The main reason is readability. Python style generally favors explicit names and conventional function definitions over clever compact syntax.

A def also gives you advantages that become important as code grows:

  • a better function name in tracebacks
  • a natural place for a docstring
  • room for type hints
  • easy expansion if the logic becomes more complex later

Compare these two examples:

python
normalize = lambda s: s.strip().lower()
python
def normalize(s: str) -> str:
    """Trim whitespace and lowercase the input."""
    return s.strip().lower()

The second version is easier to understand, easier to document, and easier to extend.

When lambda Is Still Appropriate

The warning does not mean lambda is bad. It means assigned lambdas are usually the wrong tool. Inline lambdas are still fine when the function is short and used only once.

For example, sorting with a small key function is a good use case:

python
1users = [
2    ("alice", 3),
3    ("bob", 1),
4    ("carol", 2),
5]
6
7users.sort(key=lambda item: item[1])
8print(users)

Likewise, a tiny transformation passed to map or filter can be reasonable, although many teams still prefer comprehensions for readability.

The key distinction is this: inline lambda keeps a short throwaway function close to the call site, while name = lambda ... creates a named function in a less clear form.

Refactoring an Assigned Lambda

Suppose you start with this code:

python
is_even = lambda n: n % 2 == 0

The linter wants this instead:

python
def is_even(n: int) -> bool:
    return n % 2 == 0

That looks like a small change, but it scales better. If you later need validation or logging, you can expand the function naturally:

python
1def is_even(n: int) -> bool:
2    if not isinstance(n, int):
3        raise TypeError("n must be an int")
4    return n % 2 == 0

With the lambda form, that evolution is awkward because lambda supports only a single expression.

Debugging Differences

One practical reason to prefer def is stack traces and introspection. Assigned lambdas still carry the internal name "<lambda>", which can make debugging less informative.

python
square = lambda x: x * x

print(square.__name__)

That prints "<lambda>".

With a normal function:

python
1def square(x):
2    return x * x
3
4print(square.__name__)

That prints "square", which is more useful in logs, debuggers, and profiling output.

A Good Rule of Thumb

If the function deserves a reusable name, use def. If it is a very small, local piece of behavior passed directly into another function, lambda may still be appropriate.

In modern Python, list comprehensions and generator expressions often replace simple map and filter cases anyway, which means many codebases use lambda less frequently than they used to.

Common Pitfalls

A common mistake is treating lambda as a shorter version of def in all situations. It is shorter, but not always clearer.

Another pitfall is assigning a lambda because the logic is currently tiny, then gradually growing the code around it. That creates a style warning now and a maintainability problem later.

Developers also sometimes think the warning is about performance. It is not. lambda and def are usually chosen for clarity, not speed.

Finally, do not “fix” E731 by disabling the linter unless your team has a deliberate style exception. In most codebases, replacing the assigned lambda with def is the better long-term choice.

Summary

  • 'E731 warns against assigning a lambda to a name.'
  • If the function has a reusable name, prefer def.
  • 'def improves readability, debugging, documentation, and future expansion.'
  • Inline lambda is still fine for short throwaway callbacks.
  • The warning is about code clarity and maintainability, not raw performance.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.