How to Use Python Lambda Functions

How to Use Python Lambda Functions

This in-depth tutorial will teach you how to use Python Lambda functions. You’ll understand why they are helpful in simplifying code and in the context of functional programming. Also, you’ll get acquainted with basic use cases of lambda functions, as well as advanced ones.

Lambda functions are essentially small anonymous functions that are suitable for situations where you need a simple function for a short time. You create these types of functions right where you need them. They are usually compact and just one-liners. Lambda functions make your code clean and easier to follow.

Unlike the traditional functions where the Python keyword, def, comes into play, you create this kind of function using the keyword, lambda. You’ll learn the syntax of lambda functions shortly.

Prerequisites

This tutorial is for beginner to intermediate Python programmers. However, it’s simple enough for curious minds who aren’t within the range but are interested in Python lambda functions or programming in general to follow along.

You’ll need:

Lambda Function

Imagine yourself working on a complex math problem (without a calculator) and needing to make a quick summation of a string of numbers. You could take the painful route of writing the entire equation down somewhere, but that may take a lot of time and overkill for a simple sum.

Rather than wasting your precious time, you could grab a sticky note and perform the summation. A lambda function plays a similar role in Python. It’s a function you can use to complete a simple task without having to create a “normal” function. However, like the sticky note, Python programmers use lambda functions where necessary and discard them afterwards.

How to Create a Lambda Function

You create a lambda function by typing the Python keyword, lambda, followed by the arguments of the function (you separate them with commas if more than one), then add a colon and the operation the function performs (a single operation). Here’s the syntax:

lambda (arguments): (expression)

Below is a breakdown of the above syntax:

  • lambda is the Python keyword signifying you’re creating a lambda function

  • arguments are the inputs the function takes, and they can be as many as possible (like regular functions)

  • expression is the operation the function performs (usually a single operation) and returns

It’s essential to note that lambda functions return the value of the expression. Python programmers don’t have to write the return statement explicitly.

Example

Create a simple lambda function that takes an integer and squares it:

# lambda_1.py

# Takes an integer 'x' and squares it
square = lambda x: x * x

You can see the function in lambda_1.py above covers only one line. Now, create another square function. This time, use the traditional function approach:

# lambda_2.py

# Takes an integer 'x' and squares it
def square(x):
    return x * x

The function in lambda_2.py above covers an extra line compared to the function in lambda_1.py. Although the syntaxes differ, both functions play the same role.

Lambda Functions vs. Regular Functions

Both function types possess certain qualities that make them differ from each other. Let’s consider lambda and regular functions side-by-side:

FeatureLambda FunctionRegular Function
DefinitionSIngle line using lambdadef function_name(): and a code block
NamingAnonymousHas an assigned name
SizeOne-liner, conciseCan be multiple lines for complex logic
ScopeUsually used within other functionsTypically exists independently
Return valueReturns the expression’s resultUses the Python keyword, return, to specify output

How Does Python See Lambda and Regular Functions?

You may be wondering how the Python interpreter sees and tells the difference between a lambda function and a traditional function under the hood. You'll find out soon enough.

an function has no name

Python has a dis module that translates compiled instructions the interpreter typically works on (Python bytecode) into a human-readable form. The module allows Python programmers to take a sneak peek into how Python code is translated into what the computer understands. This feature helps programmers debug codes, among other functions.

Now, you'll use the dis module on the functions in the examples lambda_1.py and lambda_2.py above to explore what happens under the hood. Run these functions on your Python console:

>>> import dis
>>> square = lambda x: x * x
>>> type(square)
<class 'function'>
>>> dis.dis(square)
  1           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                0 (x)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE
>>> square
<function <lambda> at 0x103660670>

As you can see above, using the dis() method from the dis module, you can expose the Python bytecode in a readable format that'll help you inspect how the interpreter is executing the program.

Let's see what happens with a regular function:

>>> import dis
>>> def square(x):
...    return x * x
...
>>> type(square)
<class 'function'>
>>> dis.dis(square)
  2           0 LOAD_FAST                0 (x)
              2 LOAD_FAST                0 (x)
              4 BINARY_MULTIPLY
              6 RETURN_VALUE
>>> square
<function square at 0x1063a6670>

Using the dis() method to reveal Python's interpretation shows that both functions are interpreted the same way. However, the naming differs. The function name is square for the one created using def and <lambda> for the other function defined using lambda. This naming convention is proof that lambda sees both functions differently, even though their bytecode interpretation is the same.

Using Lambda Functions

Now that you know what a lambda function is and its basic syntax, you’ll learn how to use it in your Python programs.

Simple Lambda Functions

You can use lambdas for simple operations such as adding a pair of numbers, squaring an integer or converting a string to uppercase.

Consider the examples below:

>>> # Example 1: Lambda function for adding two numbers
>>> sum = lambda x, y: x + y
>>> print(sum(3, 5))
8

>>> # Example 2: Lambda function for squaring a number
>>> square = lambda x: x * x
>>> print(square(4))
16

>>> # Example 3: Lambda function for converting a string to uppercase
>>> to_upper = lambda s: s.upper()
>>> print(to_upper("hello"))
HELLO

You can see how concise the lambdas above are. These functions come in handy when you need to sort a list of numbers or transform the data elements of a list.

Lambdas with Multiple Arguments

Like traditional functions, lambdas are also capable of accepting multiple arguments. These arguments are often separated with commas. Lambda functions with multiple arguments are usually advantageous in situations where working with data requires mixing elements from more than one source. The functions are also helpful when you’re pairing data in an operation.

Let’s assume you have a bunch of coordinates (x, y) that you need to sort. You could sort them by using the first digit of each of the coordinates. But what if you want to sort them based on the sum of each pair? A lambda will come in handy. See the breakdown below:

>>> coordinates = [(3, 2), (-1, 5), (0, 0)]
>>> sorted_coordinates = sorted(coordinates, key=lambda point: point[0] + point[1])
>>> print(sorted_coordinates)
[(0, 0), (-1, 5), (3, 2)]

In the code block above:

  • We use Python’s built-in function, sorted() to sort the coordinates list

  • sorted() takes in two arguments: the item to sort and the key parameter (optional)

  • The key parameter specifies a lambda function that computes a custom sorting key for each element in coordinates

  • The lambda function takes a single argument point, which represents each tuple in coordinates

  • point[0] and point[1] represents the x and y-coordinate respectively

  • sorted_coordinates contains the tuples from coordinates, sorted based on the sum of their x-coordinate and y-coordinate

Using Lambdas with Built-in Functions

Before you learn how to use lambdas with Python built-in, you must know about higher-order functions. In regular programming, functions often perform operations on numbers, texts, or other simple data. However, higher-order functions take this a step further. This type of function takes other functions as arguments or returns a function as the result.

Higher-order functions are a fundamental concept in functional programming. Moreover, functional programming highlights the use of functions to transform data.

There are three commonly used higher-order functions in Python: map(), filter(), and reduce. You’ll learn how to use these functions alongside lambdas.

How to Use Lambdas With Map()

map(function, iterable, *iterables)

The Python built-in, map(), takes two arguments –– function and iterable. It applies the operation of a given function to each item in an iterable (such as a list, strings, or tuples) and returns a new iterator containing the results. The function can take as many iterable arguments as possible and apply the specified function to them.

Example

>>> # Using map() with lambda function to double each element in a list
>>> numbers = [1, 2, 3, 4, 5]
>>> doubled_numbers = list(map(lambda x: x * 2, numbers))
>>> print(doubled_numbers)
[2, 4, 6, 8, 10]

In this example:

  • The function, lambda x: x * 2 is applied to each integer in numbers

  • The built-in list() is used to convert the iterator returned by map() into an expanded list that your Python console can display

How to Use Lambdas With Filter()

filter(function, iterable)

filter() takes two arguments –– function and iterable. The Python built-in works like the name implies. It creates an iterator from elements of an iterable for which the specified function returns true. In essence, it filters out elements of the iterable that return true for the function parameter. So, only elements of the iterable that return true for the function will find their way to the new iterator.

Example

>>> # Using filter() with lambda function to filter out even numbers from a list
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
>>> print(even_numbers)
[2, 4, 6]

The example above shows that:

  • lambda x: x % 2 == 0 is applied to each element of numbers

  • Only elements that return true for the function are found in the resulting list

  • The built-in list() converts the iterator returned by map() into an expanded list that your Python console can display

How to Use Lambdas With Reduce()

functools.reduce(function, iterable, [initializer])

reduce() applies a function repeatedly to items in a list, “reducing” it down to a single item. Think of the function as a machine that collects multiple ingredients and combines them according to a recipe (function) until the dish is ready.

The reduce() function is available in the functools module. It takes three arguments: the function to apply, an iterable, and an optional initializer value. The function operates cumulatively on items of the iterable, from left to right, until a single value is obtained.

Example

>>> # Using reduce() with lambda function to calculate the sum of all elements in a list
>>> from functools import reduce
>>> numbers = [1, 2, 3, 4, 5, 6]
>>> total_sum = reduce(lambda x, y: x + y, numbers, 0)
>>> print(total_sum)
21

In this example:

  • Since reduce() is available in the functools module, you have to import it from there

  • lambda x, y: x + y is applied cumulatively to the elements of numbers, from left to right, starting with 0

  • The function calculates the sum of the elements in pairs

Advanced Use Cases of Lambda Function

You have learnt how to use lambda functions for simple Python operations. Now, you’ll know and explore some advanced cases where Python programmers also incorporate lambdas.

Lambda Functions in List Comprehensions

List comprehension allows Python programmers to define and create lists on the go. When you require a quick transformation or need to apply a filter to an existing list, introducing a lambda into the list comprehension offers clarity and conciseness.

Examples

Consider below various tasks where lambda functions are used within list comprehensions:

1. Using lambda function to double each element in a list using list comprehension

>>> numbers = [1, 2, 3, 4, 5, 6]
>>> doubled_numbers = [(lambda x: x * 2)(x) for x in numbers]
>>> print(doubled_numbers)
[2, 4, 6, 8, 10, 12]

In the above example:

  • For each element x in numbers list, lambda x: x * 2 is defined and called with x current value

  • The lambda function takes an input x and returns x * 2

  • The doubled values are collected in the doubled_numbers list

2. Filtering even numbers from a list using list comprehension with a lambda function

>>> numbers = [1, 2, 3, 4, 5, 6]
>>> even_numbers = [x for x in numbers if (lambda x: x % 2 == 0)(x)]
>>> print(even_numbers)
[2, 4, 6]

In this example:

  • The function checks if the value of x is even for the modulus operation, x % 2 == 0

  • If the result is True, it means x is even and included in the even_numbers list

3. Combining elements from two lists using list comprehension with a lambda function

>>> names = ["Alice", "Bob", "Charlie"]
>>> ages = [25, 39, 34]
>>> person_info = [(lambda name, age: (name, age) )(name, age) for name, age in zip(names, ages)]
>>> print(person_info)
[('Alice', 25), ('Bob', 39), ('Charlie', 34)]

In the above code block:

  • person_info iterates over corresponding elements from the names and ages list using the zip() function

  • zip() is used to combine multiple iterables into a single iterable of tuples

  • The list comprehension generates a list of tuples where each tuple contains a name and corresponding age, respectively

Sorting with Lambda

Python is equipped with a built-in sorted() function that allows programmers to sort iterables. But what makes the function powerful is its key argument, which will enable you to customize how you want the function to sort an iterable. You can use a lambda function to define custom sorting criteria.

The ability to use lambda for customization allows for flexible on-the-fly sorting without explicitly creating a separate comparison function.

Examples

Take a look at the simple examples below:

1. Sorting a list of tuples based on the second element using lambda function

>>> points = [(1, 5), (3, 2), (2, 7)]
>>> sorted_points = sorted(points, key=lambda x: x[1])
>>> print(sorted_points)
[(3, 2), (1, 5), (2, 7)]

In the example above:

  • sorted() sorts the points list based on the custom key provided by the lambda function

  • lambda x: x[1] means the list should be sorted based on the element in the second index of each tuple

2. Sorting a list of dictionaries based on a specific key using a lambda function

>>> students = [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
>>> sorted_students = sorted(students, key=lambda x: x['age'])
>>> print(sorted_students)
[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

In the code block above:

  • sorted() function sorts the list students based on a custom sorting key offered by a lambda function

  • lambda x: x['age'] computes the sorting based on the age of each student in ascending order

Lambda Functions and Closures

A closure in Python is simply a nested function that has access to the names and variables that are within the scope of the outer function, even after the outer function has finished executing or returned. Imagine a function carrying a backpack. Inside that backpack are variables from the environment where the function was born, even if the environment no longer exists.

Closure resembles private variables in object-oriented programming. They allow Python programmers to bundle data with specific behaviors (functions).

Here’s a simple example of closure in Python:

# simple_closure.py

def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function


add_five = outer_function(5)
print(add_five(10))

>>> 15

In simple_closure.py above:

  • outer_function defines a closure by returning inner_function

  • inner_function captures the variable x from the outer function’s scope

  • When add_five is called with an argument 10, it adds 10 to the captured value of x (which is 5), therefore, returns 15

Closure With Lambda

Lambda functions can serve as the inner function within a closure. This feature allows Python programmers to encapsulate a behavior that needs to access variables from the outer function’s scope.

Example

# lambda_closure.py

def outer_function():
    x = 10
    return lambda y: x + y

add_ten = outer_function()
print(add_ten(5))

>>> 15

In lambda_closure.py above:

  • lambda y: x + y serves as the inner function

  • The inner function captures x from the outer function and adds it to y

In addition, Python programmers often use lambda within closure for concise operations. It’s necessary where defining a separate function is just an overkill.

Example

# concise_lambda_closure.py

def outer_function(operation):
    return lambda x, y: operation(x, y)


add = outer_function(lambda a, b: a + b)
multiply = outer_function(lambda a, b: a * b)

print(add(3, 5))
print(multiply(3, 5))

>>> 8
>>> 15

In concise_lambda_closure.py:

  • outer_function takes a function, operation, as argument

  • It returns a closure that applies the given operation (`add` and multiply) to its argument x and y

Conclusion

In this in-depth tutorial, you have:

  • Learned how to use lambda functions in your Python programs

  • Learned how lambdas are helpful in simplifying code and their role in functional programming

  • Explored simple and advanced use cases of lambda functions

Lambda functions are like quick kitchen hacks. They are temporary solutions for specific tasks, similar to improvising in cooking. Regular Python functions are like popular recipes — structured and reusable. Both are essential. You need to know about them and when to use them.


Thanks for reading! If you found this article helpful (which I bet you did 😉), got a question or spotted an error/typo... do well to leave your feedback in the comment section.

And if you’re feeling generous (which I hope you are 🙂) or want to encourage me, you can put a smile on my face by getting me a cup (or thousand cups) of coffee below. :)

Also, feel free to connect with me via LinkedIn.