Python Tutorials · Python Functions

Python Lambda

Learn all about Python Lambda in this comprehensive tutorial.

5 min read beginner
  • A lambda function is a small anonymous function.
  • The expression is executed and the result is returned:
  • The power of lambda is better shown when you use them as an anonymous function inside another function.
  • Lambda functions are commonly used with built-in functions like map(), filter(), and sorted().

Lambda Functions

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

Syntax

The expression is executed and the result is returned:

python

Lambda functions can take any number of arguments:

python
python

Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function inside another function.

Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

python

Use that function definition to make a function that always doubles the number you send in:

python

Or, use the same function definition to make a function that always triples the number you send in:

python

Or, use the same function definition to make both functions, in the same program:

python
Note: Use lambda functions when an anonymous function is required for a short period of time.

Lambda with Built-in Functions

Lambda functions are commonly used with built-in functions like map(), filter(), and sorted().

The map() function applies a function to every item in an iterable:

python

The filter() function creates a list of items for which a function returns True:

python

The sorted() function can use a lambda as a key for custom sorting:

python
python

Module quiz

2 questions
1

Which of the following is true about Python Lambda?

2

What is the most common pitfall when working with Python Lambda?

Answer all questions to submit.