Skip to Content
Articles

Python Lambda Functions Explained (With Examples)

What is a lambda function in Python?

A Python lambda function is an anonymous function that lets you write quick, inline functions without using the def keyword. If you’ve wondered "what is lambda in Python?" - it’s essentially a way to create small functions on the fly for specific tasks. Lambda programming in Python is useful when a function is passed as an argument or when you need a simple operation. The syntax of Python’s lambda function is as follows:

lambda arguments: expression 

In this syntax:

  • lambda: This keyword tells Python that a lambda function is defined.
  • arguments: These are the inputs that the function takes. Can be one, many, or even none.
  • expression: This is what gets evaluated and returned. It must be a single expression with no return keyword, as it returns the result automatically.

But why use lambda functions? Here are some of their key features:

  • Anonymous: They don’t have a name unless they’ve been assigned one.
  • Single-expression only: They can’t include loops, multiple statements, or blocks. Just one expression is required.
  • No return keyword: The expression’s result is returned automatically.
  • Can take multiple arguments: You can pass in more than one input, though you can’t use default values or type hints.
  • Often used inline: They’re a good fit for quick operations inside functions like map(), filter(), or sorted().

Now that you know what lambda functions are, here are some examples.

Python lambda function examples

Lambda functions are used when defining a full function feels too much. Here are some examples that show how they can simplify tasks.

Using lambda functions to square a number

The lambda function returns the square of a given number:

square =lambda x: x **2
print(square(5))

The output of this code is:

25

This lambda function takes a single input x and returns x to the power of 2.

Lambda function with conditional statement

We need to check if a number is even or odd and return a corresponding message:

even_or_odd =lambda x:"Even"if x %2==0else"Odd"
print(even_or_odd(7))

The output of this code is:

Odd

The lambda uses a conditional expression to check whether the number is divisible by 2. If yes, it returns "Even" otherwise, it returns "Odd".

Finding the larger of two numbers using lambda functions

Here, we’re comparing two numbers and returning the larger one:

max_value =lambda a, b: a if a > b else b
print(max_value(10,25))

The output of this code is:

25

The lambda checks which of the two inputs is greater and returns that value. It’s a basic one-liner that replaces a multi-line if-else block.

Using lambda function in list comprehension

Applying a lambda to each item in a list to calculate double the value:

nums =[1,2,3,4]
squares =[(lambda x: x **2)(n)for n in nums]
print(squares)

The output of this code is:

[1, 4, 9, 16]

Each number n in the list is passed to a lambda function that returns its square. The result is a new list of squared values.

Lambda programming to filter names starting with ‘A’

Filtering a list of names to return only those names that begin with the letter ‘A’:

names =["Alice","Bob","Anna","Tom"]
a_names =[name for name in names if(lambda x: x.startswith('A'))(name)]
print(a_names)

The output of this code is:

['Alice', 'Anna']

The lambda checks whether each name starts with the letter 'A', and the list comprehension keeps only those that return True.

Beyond standalone use, lambda functions are also helpful when combined with built-in functions. Let’s explore them.

Using lambda functions with built-in functions

Built-in functions are perfect when working with lists or other iterable data. When combined with lambda functions, they allow for quick, expressive operations.

Double the numbers with map()

The map() function here creates a new list where each number is multiplied by 2:

numbers =[1,2,3,4]
doubled =list(map(lambda x: x *2, numbers))
print(doubled)

The output of the code is:

[2, 4, 6, 8]

Extract even numbers with filter()

The filter() function uses the lambda to test each number, returning only those that pass the condition:

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

The output for this code is:

[2, 4, 6]

Multiply all numbers with reduce()

reduce() applies the lambda step by step, multiplying values from left to right:

from functools importreduce
numbers =[1,2,3,4]
product =reduce(lambda x, y: x * y, numbers)
print(product)

The output of this code is:

24

So, how does lambda compare to the regular functions?

Lambda functions vs regular functions in Python

Both lambda functions and regular functions are used to define functionality, but they differ in how they’re written, used, and what they’re best suited for. Here’s a comparison:

Feature Lambda Functions Regular Functions
Definition An anonymous function defined using lambda A named function defined using def
Naming Usually unnamed (used inline) Always has a name
Syntax lambda parameters: expression def function_name(parameters):
    statements
Statements Only a single expression allowed Can contain multiple statements, including conditionals and loops
Documentation Cannot include docstrings Supports docstrings for inline documentation
Reusability Typically used for short, one-time operations Ideal for reuse and larger blocks of logic

It’s all about using the right tool for the job: Lambdas are great for quick tasks, while regular functions are better when operations get bigger.

Conclusion

In this article, we explored Python’s lambda functions, what they are, how they differ from regular functions, and where they come in handy. From basic expressions to combining them with built-in functions like map(), filter(), and reduce(), you now have a solid handle on writing and recognizing anonymous functions.

If you’re ready to practice what you’ve learned or want to explore more about functional programming in Python, check out the Learn Python 3 course on Codecademy.

Frequently asked questions

1. Why is it called lambda in Python?

The term "lambda" comes from the lambda calculus, a formal system of mathematics and computer science expressing computation. Python borrowed the name to define anonymous functions.

2. What is the benefit of lambda in Python?

Lambda functions let you write quick, throwaway functions without formally defining them using def. They’re useful when passing a function as an argument to tools like map(), filter(), or sorted().

3. How many lambda functions are there in Python?

There’s just one type of lambda function in Python. However, you can define as many as you need, and each can be customized with different logic depending on the task.

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team

Learn more on Codecademy

AltStyle によって変換されたページ (->オリジナル) /