In this tutorial, you’ll learn all about 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.
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.
#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: 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:
#2. Next, let’s rewrite another simple function add() that takes into numbers, num1 and num2, and returns their sum, num1 + num2.
return 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.
>>> (lambda num1, num2: num1 + num2)(3,7)
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.
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)
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.
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.
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.
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.
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.
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.
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.
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 as it’ll use the item at index 1, the price, to sort the dictionary.
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.
Google Knowledge Panel are the boxes that appear on Google when you search for specific entities such as people, organizations, or places. They are meant to give you a quick understanding through boxes about the information you are looking for.
Statistical analysis provides a systematic and objective approach to extracting meaningful insights from data. It helps in making evidence-based decisions, drawing reliable conclusions, and understanding the inherent variability and uncertainties in various processes and systems.