Sitemap

Demystifying Python Lambda Functions

Life with Python #18

Sometimes in life (and in python), you need something done quickly and efficiently without fuss. That’s where lambda functions come in. Let‘s see how they work.

Get Prathik C’s stories in your inbox

Join Medium for free to get updates from this writer.

In this post, I’ll break down what lambda functions are, when to use them, and — just as importantly — when not to.

What Is a Lambda Function?

At its core, a lambda function is an anonymous function — a function defined without a name. The syntax is deliberately minimalist:

lambda arguments: expression

Unlike a standard Python function defined with def, a lambda function:

  • Contains only a single expression (no statements or multiline logic).
  • Returns the result of that expression implicitly.
  • Is often used in contexts where a function is needed temporarily.

Simple Example:

cube = lambda x: x ** 3
print(cube(5)) # Output: 125

This is equivalent to:

def cube(x):
return x ** 3

So why do we need lambda at all if def works just fine?

The Real Use Cases

Lambda functions are best used in situations where:

  • The function is simple and used once or twice.
  • You want to avoid polluting your namespace with named functions.
  • You’re working with functional-style tools like map(), filter(), or sorted().

1. With sorted() for Custom Sorting:

data = [(1, 'apple'), (3, 'banana'), (2, 'cherry')]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
# Output: [(1, 'apple'), (3, 'banana'), (2, 'cherry')]

Here, lambda x: x[1] extracts the second element of each tuple for comparison and does sorting on the basis of that element.

2. With map():

numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x ** 3, numbers))
print(squares)
# Output: [1, 8, 27, 64]

3. With filter():

nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)
# Output: [2, 4, 6]

3. Lambda Inside Other Functions (Closures):

Lambda functions are often used inside higher-order functions to create closures:

def make_incrementer(n):
return lambda x: x + n
inc_by_3 = make_incrementer(3)
print(inc_by_3(10))
# Output: 13

This is particularly useful when building configurable functions dynamically — something you’ll supposedly see a lot in machine learning pipelines.

Behind the Scenes: How Python Treats Lambdas

Technically, a lambda function is just a function object like any other. Python compiles it to a code object and stores it just like a function defined with def.

type(lambda x: x)  # <class 'function'>

There’s nothing magical going on — its just a shortcut.

Limitations

Lambda functions aren’t a replacement for regular functions. They come with important limitations:

  1. Single expression only: You can’t have multiple statements, assignments, or try-except blocks.
  2. No annotations or docstrings: They’re anonymous and undocumented by nature.
  3. Readability: Overuse, especially for anything non-trivial, makes code harder to understand.

Here’s a bad example:

f = lambda x: x if x > 0 else (0 if x == 0 else -x)

Better, more readable alternative:

def absolute_value(x):
if x > 0:
return x
elif x == 0:
return 0
else:
return -x

Lambdas vs. Named Functions: When to Use Which

To summarise:

lambda vs def

Lambda functions aren’t essential for writing good Python code, but they are a powerful tool for writing clean, concise logic when used properly. The key is to keep them simple. If you’re finding yourself nesting them, embedding them in list comprehensions, or adding conditional logic inside — take a step back. A named function is probably a better fit.

Used wisely, lambda can help make your code more neat and expressive. Used poorly, it becomes a source of bugs and obfuscation.

So it is important to know the trade-offs. Make sure to use the right tool for the job — there’s no need to take a gun to a knife fight (usually!) :D

Until next time:)