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: 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. #1. Consider the following function square(), that takes in a number, num, as the argument and returns the square of the number. You can call the function with arguments and verify that it’s working correctly. You can assign this lambda expression to a variable name, say, square1 to make the function definition more concise: square1 = lambda num: numnum 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 numnum. After we’ve identified these, we can plug them in the lambda expression and call it with an argument, as shown: 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. Let’s call the add() function with two numbers as the arguments: In this case, num1 and num2 are the two parameters and the return value is num1 + num2. 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. 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.
When writing functions that take in default values for certain parameters as lambda expressions, you can specify the default value when defining the parameters.
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: 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. As the map() function returns a map object, we should cast it into a list. ▶️ Check out this tutorial on map() function in Python.
#2. Using Lambda with filter()
Let’s define nums, a list of numbers: 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. 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.
#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. To use the reduce() function, you’ll have to import it from Python’s built-in functools module: 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.
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.
#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. 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. 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. 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’. 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. ▶️ Learn more about sorting Python lists.
#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. To get the key-value pairs of a dictionary as a list of tuples, you can use the built-in dictionary method .items(): 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. 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 sorting a Python dictionary 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.
Next, learn how to perform floor division in Python.