In this tutorial, you’ll learn all about how to use lambda functions in Python – from the syntax to define lambda functions to the different use cases with code examples.

In Python, lambdas are anonymous functions that have a concise syntax and can be used with other helpful built-in functions. By the end of this tutorial, you’ll have learned how to define lambda functions and when you should consider using them over regular Python functions.

Let’s begin!

Python Lambda Function: Syntax and Examples

Here’s the general syntax to define a lambda function in Python:

lambda parameter(s):return value

In the above general syntax:

  • lambda is the keyword you should use to define a lambda function, followed by one or more parameters that the function should take.
  • There’s a colon separating the parameters and the return value.

💡 When defining a lambda function, you should ensure that the return value is computed by evaluating an expression that spans a single line of code. You’ll understand this better when we code examples.

Python Lambda Function Examples

The best way to understand lambda functions is to start by rewriting regular Python functions as lambda functions.

👩🏽‍💻 You can code along in a Python REPL or using this Python online compiler.

#1. Consider the following function square(), that takes in a number, num, as the argument and returns the square of the number.

def square(num):
    return num*num

You can call the function with arguments and verify that it’s working correctly.

>>> square(9)
81
>>> square(12)
144

You can assign this lambda expression to a variable name, say, square1 to make the function definition more concise: square1 = lambda num: num*num and then call the square1 function with any number as the argument. However, we know that lambdas are anonymous functions, so you should avoid assigning them to a variable.

For the function square(), the parameter is num and the return value is num*num. After we’ve identified these, we can plug them in the lambda expression and call it with an argument, as shown:

>>> (lambda num: num*num)(2)
4

This is the concept of Immediately Invoked Function Expression, where we call a function right after defining it.

#2. Next, let’s rewrite another simple function add() that takes into numbers, num1 and num2, and returns their sum, num1 + num2.

def add(num1,num2):
    return num1 + num2

Let’s call the add() function with two numbers as the arguments:

>>> add(4,3)
7
>>> add(12,5)
17
>>> add(12,6)
18

In this case, num1 and num2 are the two parameters and the return value is num1 + num2.

>>> (lambda num1, num2: num1 + num2)(3,7)
10

Python functions can also take default values for parameters. Let’s modify the definition of the add() function and set the default value of the num2 parameter to 10.

def add(num1, num2=10):
    return num1 + num2

In the following function calls:

  • In the first function call, the value of num1 is 1 and the value of num2 is 3. When you pass in the value for num2 in the function call, that value is used; the function returns 4.
  • However, if you pass in only one argument (num1 is 7), the default value of 10 is used for num2; the function returns 17.
>>> add(1,3)
4
>>> add(7)
17

When writing functions that take in default values for certain parameters as lambda expressions, you can specify the default value when defining the parameters.

>>> (lambda num1, num2 = 10: num1 + num2)(1)
11

When Should You Use Lambda Functions in Python?

Now that you’ve learned the basics of lambda functions in Python, here are a few use cases:

  • When you have a function whose return expression is a single line of code and you don’t need to reference the function elsewhere in the same module, you can use lambda functions. We’ve also coded a few examples to understand this.
  • You can use lambda functions when using built-in functions, such as map(), filter(), and reduce().
  • Lambda functions can be helpful in sorting Python data structures such as lists and dictionaries.

How to Use Python Lambda with Built-In Functions

#1. Using Lambda with Map()

The map() function takes in an iterable and a function and applies the function to each item in the iterable, as shown:

python-lambda-with-map

Let’s create a nums list and use the map() function to create a new list that contains the square of each number in the nums list. Notice the use of lambda function to define the squaring operation.

>>> nums = [4,5,6,9]
>>> list(map(lambda num:num*num,nums))
[16, 25, 36, 81]

As the map() function returns a map object, we should cast it into a list.

▶️ Check out this tutorial on Python map function.

#2. Using Lambda with Filter()

Let’s define nums, a list of numbers:

>>> nums = [4,5,6,9]

Suppose you’d like to filter this list and retain only the odd numbers.

You can use Python’s built-in filter() function.

The filter() function takes in a condition and an iterable: filter(condition, iterable). The result contains only the elements in the original iterable that satisfy the condition. You can cast the returned object into a Python iterable such as list.

python-lambda-with-filter

To filter out all the even numbers, we’ll retain only the odd numbers. So the lambda expression should be lambda num: num%2!=0. The quantity num%2 is the remainder when num is divided by 2.

  • num%2!=0 is True whenever num is odd, and
  • num%2!=0 is False whenever num is even.
>>> nums = [4,5,6,9]
>>> list(filter(lambda num:num%2!=0,nums))
[5, 9]

#3. Using Lambda with Reduce()

The reduce() function takes in an iterable and a function. It reduces the iterable by applying the function iteratively on the items of the iterable.

python-lambda-with-reduce

To use the reduce() function, you’ll have to import it from Python’s built-in functools module:

>>> from functools import reduce

Let’s use the reduce() function to compute the sum of all numbers in the nums list. We define a lambda expression: lambda num1,num2:num1+num2, as the reducing sum function.

The reduction operation will occur like this: f(f(f(4,5),6),9) = f(f(9,6),9) = f(15,9) = 24. Here, f is the summing operation on two items of the list, defined by the lambda function.

>>> from functools import reduce
>>> nums = [4,5,6,9]
>>> reduce(lambda num1,num2:num1+num2,nums)
24

If you are unsure about sums, you can check this on understanding Python’s sum function.

Python Lambda Functions to Customize Sorting

In addition to using lambda functions with built-in Python functions, such as map(), filter(), and reduce(), you can also use them to customize built-in functions and methods used for sorting.

img

#1. Sorting Python Lists

When working with Python lists, you’ll often have to sort them based on certain sorting criteria. To sort Python lists in place, you can use the built-in sort() method on them. If you need a sorted copy of the list, you can use the sorted() function.

The syntax to use Python’s sorted() function is sorted(iterable, key=...,reverse= True | False).

– The key parameter is used to customize the sort.
– The reverse parameter can be set to True or False; the default value is False.

When sorting lists of numbers and strings, the default sorting is in ascending order and alphabetical order, respectively. However, you may sometimes want to define some custom criterion for sorting.

Consider the following list fruits. Suppose you’d like to obtain a sorted copy of the list. You should sort the strings according to the number of occurrences of ‘p’ in them – in the decreasing order.

>>> fruits = ['apple','pineapple','grapes','mango']

It’s time to use the optional key parameter. A string is an iterable in Python and to obtain the number of occurrences of a character in it, you can use the built-in .count() method. So we set the key to lambda x:x.count('p') so that the sorting is based on the number of times ‘p’ occurs in the string.

>>> fruits = ['apple','pineapple','grapes','mango']
>>> sorted(fruits,key=lambda x:x.count('p'),reverse=True)
['pineapple', 'apple', 'grapes', 'mango']

In this example:

  • The key to sort on is the number of occurrences of the character ‘p’, and it’s defined as a lambda expression.
  • As we’ve set the reverse parameter to True, the sort occurs in the decreasing order of the number of occurrences of ‘p’.

In the fruits list, ‘pineapple’ contains 3 occurrences of ‘p’, and the strings ‘apple’, ‘grapes’, and ‘mango’ contain 2, 1, and 0 occurrences of ‘p’, respectively.

Understanding Stable Sort

Consider another example. For the same sorting criterion, we’ve redefined the fruits list. Here, ‘p’ occurs in the strings ‘apple’ and ‘grapes’ twice and once, respectively. And it never occurs in the strings ‘mango’ and ‘melon’.

>>> fruits = ['mango','apple','melon','grapes']
>>> sorted(fruits,key=lambda x:x.count('p'),reverse=True)
['apple', 'grapes', 'mango', 'melon']

In the output list, ‘mango’ comes before ‘melon’ even though they both do not have the character ‘p’. But why is this the case? The sorted() function performs a stable sort; so when the count of ‘p’ is equal for two strings, the order of elements in the original fruits list is preserved.

As a quick exercise, swap the positions of ‘mango’ and ‘melon’ in the fruits list, sort the list based on the same criterion, and observe the output.

▶️ Learn more about how to sort list in Python.

#2. Sorting a Python Dictionary

You can also use lambdas when sorting Python dictionaries. Consider the following dictionary price_dict that contains items and their prices.

>>> price_dict = {
... 'Milk':10,
... 'Honey':15,
... 'Bread':7,
... 'Candy':3
... }

To get the key-value pairs of a dictionary as a list of tuples, you can use the built-in dictionary method .items():

>>> price_dict_items = price_dict.items()
dict_items([('Milk', 10), ('Honey', 15), ('Bread', 7), ('Candy', 3)])

In Python, all iterables: lists, tuples, strings, and more, follow zero-indexing. So the first item is at index 0, the second item is at index 1, and so on.

We’d like to sort by the value, which is the price of each item in the dictionary. In each tuple in the price_dict_items list, the item at index 1 is the price. So we set the key to lambda x:x[1] as it’ll use the item at index 1, the price, to sort the dictionary.

>>> dict(sorted(price_dict_items,key=lambda x:x[1]))
{'Candy': 3, 'Bread': 7, 'Milk': 10, 'Honey': 15}

In the output, the dictionary items have been sorted in ascending order of prices: starting with ‘Candy’, priced at 3 units to ‘Honey’, priced at 15 units.

▶️ To learn more, check out this detailed guide on Python dictionary sorting by key and value.

Summing Up

And there you have it! You’ve learned how to define lambda functions and use them effectively with other Python built-in functions. Here’s a summary of the key takeaways:

  • In Python, lambdas are anonymous functions that can take in multiple arguments and return a value; the expression to be evaluated to generate this return value should be one line of code. They can be used to make small function definitions more concise. 
  • To define the Lambda function you can use the syntax: lambda parameter(s): return value.
  • Some of the important use cases include using them with map(), filter(), and reduce() functions and as the key parameter to customize sorting of Python iterables.

Happy coding!

Here’s more on Lambda, Python & Coding!