Lambda Functions in Python (with Examples)

by SkillAiNest

Lambda functions are one of those Python features that seem confusing at first but turn out to be surprisingly simple. They are small, anonymous functions that you can write in one line and use immediately.

In this tutorial, you’ll learn what lambda functions are, how they work, and when they’re useful. We will cover the most common use cases (including filter(), map(), sorted()and pandas) so you can recognize lambda functions in real code and start using them with confidence.

What is lambda function in python?

A lambda function is an anonymous function, meaning it has no name. It can take any number of arguments, but evaluates only one expression, and it automatically returns the result of that expression.

The general syntax for a lambda function is: lambda parameters: expression. Here’s a simple example that breaks it down:

Anatomy of a lambda function.Anatomy of a lambda function.

You will see the terms ‘lambda expression’ and ‘lambda function’ used interchangeably. An expression is the syntax you write. A function is something that Python creates from it. For practical purposes, they mean the same thing.

Each lambda expression consists of three parts:

  • gave lambda Keywordwhich tells Python that you are defining an anonymous function (like def for regular work)
  • gave Parameterswhich act just like function parameters, are separated by commas.
  • gave expressionwhich is evaluated and returned automatically.

Unlike a regular function, you don’t use return The keyword lambda expression returns whatever it evaluates to.

Lambda functions vs regular functions

Before we go any further, let’s compare the lambda function with a regular function that has been defined. def. This table covers the differences you’ll most often encounter:

FeatureLambda functionregular function (def)
Naminganonymous (no function name)is always a function name.
Syntaxlambda x: x + 1def func(x): return x + 1
returnImplicit (result of expression)Usually through the obvious return
The bodyA single expression onlyMultiple statements are allowed.
DocstringsNot supported.Supported by
Best forShort, one-time operationReusable or complex logic

One thing worth calling: you can do Assign the lambda to the variable, like so:

increment = lambda x: x + 1
increment(2)
# Output:
# 3

But PEP 8Python’s official style guide recommends against it. When you assign a lambda to a variable, you’re just giving a name to an anonymous function, which defeats its purpose. Use if you need a named, reusable function. def Instead

Lambda vs standard functionLambda vs standard function

How Lambda Functions Work

You can call the lambda immediately by wrapping it in parentheses:

(lambda x: x + 1)(2)
# Output:
# 3

This pattern is sometimes called a Immediately Invoked Function Expression (IIFE). You define the function and call it in the same line. This is useful when you need a quick calculation without storing anything.

Lambda functions also support multiple parameters. Separate them with commas, just like a regular function:

(lambda x, y, z: x + y + z)(3, 8, 1)
# Output:
# 12

A lambda can also return multiple values ​​wrapped in a tuple:

(lambda x, y: (x + y, x * y))(3, 4)
# Output:
# (7, 12)

You can also use conditional logic inside a lambda. A single if/else Perfectly readable and practically common:

(lambda x: x if x > 10 else 10)(5)
# Output:
# 10

That said, avoid nesting in lambda. Compare these two methods:

# Lambda with nested conditions (hard to read)
(lambda x: x * 10 if x > 10 else (x * 5 if x < 5 else x))(11)
# Output:
# 110
# Regular function (much clearer)
def check_conditions(x):
    if x > 10:
        return x * 10
    elif x < 5:
        return x * 5
    else:
        return x

print(check_conditions(11))
# Output:
# 110

Both back 110but regular functions are much easier to read and maintain. Access it when your logic requires more than one condition. def.

Lambda with built-in functions

Lambda functions are most useful when passed directly to built-in functions. Here are four of the most common pairings.

1. filter()

filter() Takes a function and an iterable, and returns only the items where the function evaluates to. True:

numbers = (33, 3, 22, 2, 11, 1)
result = list(filter(lambda x: x > 10, numbers))
print(result)
# Output:
# (33, 22, 11)

2. map()

map() Applies a function to each item iteratively and returns the transformed result:

numbers = (1, 2, 3, 4, 5)
result = list(map(lambda x: x * 10, numbers))
print(result)
# Output:
# (10, 20, 30, 40, 50)

An important difference from filter(): map() Always returns with the same number of items as the original.

3. reduce()

reduce() Applies a function to reusable objects as a whole, reducing them to a single value. You will need to import it from functools Module:

from functools import reduce

numbers = (1, 2, 3, 4, 5)
total = reduce(lambda x, y: x + y, numbers)
print(total)
# Output:
# 15

Lambda takes two arguments at a time: the accumulated result and the next object. For common combinations such as sums or minimums, Python’s built-in sum(), min()and max() are easy. reduce() Shines when you need custom aggregation logic.

4. sorted()

sorted() Returns a newly sorted list. By passing a lambda to it key parameters, you can control what is arranged:

students = (("Alice", 88), ("Bob", 72), ("Clara", 95))
result = sorted(students, key=lambda student: student(1))
print(result)
# Output:
# (('Bob', 72), ('Alice', 88), ('Clara', 95))

This sorts the list of tuples by the second factor (score) instead of the first. You can sort by any calculated value like this, which makes sorted() Extremely practical with a lambda.

Lambda with list comprehensions

You may encounter lambda functions within list comprehensions:

operations = ((lambda x: x ** 2)(n) for n in (1, 2, 3, 4))
print(operations)
# Output:
# (1, 4, 9, 16)

This works, but there is an easier way to write it:

operations = (n ** 2 for n in (1, 2, 3, 4))
print(operations)
# Output:
# (1, 4, 9, 16)

Same result, less complexity. In most cases, a simple list comprehension is cleaner than wrapping a lambda inside one. You’re more likely to encounter this in existing code than need it yourself, so recognize it but don’t default to it.

A case where lambdas in list comprehensions do it Makes sense when you’re listing functions:

multipliers = (lambda x, n=n: x * n for n in range(1, 4))
print(multipliers(0)(5))  # 5
print(multipliers(1)(5))  # 10
print(multipliers(2)(5))  # 15

Each lambda gets a different value. ncreating a reusable set of functions. This leads us to a related concept.

Lambda as a function factory (closed)

You can return a lambda from a regular function to create special functions on the fly:

How closures work with lambdas.How closures work with lambdas.

here, make_multiplier() Returns a lambda that “remembers” the value of n from the associated function. It is called closure. Every call make_multiplier() Creates a new function with its captured value.

This is useful when you need similar functions that differ by one parameter.

Lambda with Pandas

Lambda functions pair well with pandas for quick data transformation. You will see them often. .apply() And .map() Data frames and series methods.

Here’s an example that creates a new column based on the values ​​in an existing column:

import pandas as pd

df = pd.DataFrame({"score": (45, 82, 67, 91, 38)})
df("pass_fail") = df("score").map(lambda x: "Pass" if x >= 60 else "Fail")
print(df)
   score pass_fail
0     45      Fail
1     82      Pass
2     67      Pass
3     91      Pass
4     38      Fail

For rowwise operations across multiple columns, use .apply() with the axis=1:

df = pd.DataFrame({"first": (10, 20, 30), "second": (5, 15, 25)})
df("total") = df.apply(lambda row: row("first") + row("second"), axis=1)
print(df)
   first  second  total
0     10       5     15
1     20      15     35
2     30      25     55

Note that for simple arithmetic or comparisons, Pandas’ built-in vectorized operations (eg df("score") >= 60) are faster and more readable. With lambdas .apply() And .map() are most useful when the transformation involves logic that cannot be expressed as a vectorized operation.

If you’re working with data in Python, you’ll likely encounter lambdas with pandas a lot. Our Advanced Data Cleaning in Python course covers more of these patterns as part of the Data Analyst and Data Scientist career paths.

Advantages and Disadvantages of Lambda Functions

Advantages:

  • Compact syntax for simple, one-time operations
  • As higher order functions can be transferred directly. filter(), map()and sorted()
  • (IIFE) can be invoked immediately without specifying a named function.
  • Useful when an API expects a short function argument.

Disadvantages:

  • Limited to one expression (no loops, no multiple statements)
  • Domestic situations quickly become illegible.
  • Cannot include docstrings or variable assignments
  • Difficult to debug because they appear as Instead of the name of the descriptive function in the tracebacks

Best practice

  • Keep them simple. If your lambda needs more than one line of logic, use def function instead.
  • Do not assign lambdas to variables. PEP 8 discourages this. Define a regular function if you need to reuse it.
  • Prefer list comprehensions for simple transformations. (x ** 2 for x in numbers) is clear from list(map(lambda x: x ** 2, numbers)) In most situations.
  • Use lambdas inline. They perform best when passed directly as arguments to functions such as sorted(), filter()and Panda. .apply().

wrap up

Lambda functions are a small but useful tool in Python. They let you write short, unusual functions right where you need them, and they pair naturally with built-in functions and libraries like Pandas. Keep them simple, use them inline, and reach them. def When your logic is extended by a single expression.

If you’re looking to sharpen your Python skills, our Intermediate Python for AI Engineering course is a great next step in the AI ​​engineering path to a Python career. And if you’re focusing on data science, our Advanced Data Cleaning in Python course puts lambda functions to work as part of a data scientist career path.

Frequently Asked Questions

Why is it called a lambda function?

The name comes from lambda calculus, a mathematical system for expressing calculus developed in the 1930s. Python borrowed the term to describe small, anonymous functions.

Can a lambda function have multiple lines?

No. Lambda functions are limited to only one expression. If you need multiple lines of logic, conditionals, or statements. try/exceptUse a regular function with def.

When should I use a lambda function instead of a def?

Use lambdas when you need a short, one-time function that you pass directly as an argument, such as sorting by a custom key or filtering a list. If you plan to reuse the function or the logic is more than one expression, def is a better choice.

Can I use lambda functions with pandas?

Yes lambda functions work well with pandas methods eg .apply() And .map() For quick changes in data frames and series. These are a common pattern for creating new columns based on existing data.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro