Lambda functions in Python can be thought of as shorthand functions, often used when the coder is being a little lazy and doesn’t feel like fully defining a function (we’re not judging). Though they look very different from a standard function that you would declare using the def keyword, they execute in much the same way. The primary difference is that they only run a single expression. Lambda functions are also known as anonymous functions.
Lambda functions allow you to create small, single-use functions that can save time and space in your code. They ares also useful when you need to call a function that expects a function as an argument for a callback such as Map() and Filter() . But what makes a function lambda? And how can you implement them in your code in a practical manner? Read on, and we’ll attempt to explain that very thing. Unlike lambda functions, we’re going to go into quite a bit of detail, and maybe even help you improve code in your next script.
What is a Python Lambda Function?
First and foremost, a lambda function can only execute a single expression. If you need more than that, you’ll have to stick to defining a full function the conventional way. Expressions cannot return a value; however, the lambda function can return function objects.
A lambda function can take any number of arguments as its input. Similarly, it can output any number of arguments as well. The critical point is that your arguments must all pack into a single expression. Unlike regular functions, lambda expressions are declared with no name (hence the “anonymous function” mentioned above).
Making a Python Lambda Function
The basic syntax of a lambda function in Python is the same in all cases. It goes;
lambda argument/arguments: expression
As mentioned, there can be as many arguments as you like, but there can only be one expression. But let’s look at an actual example of a lambda function.
Let’s say we want to create a function for computing the remainder of a division. We would first create a label for our lambda function, declare that it is, in fact, a lambda function, set our input argument, and finally perform our function. It would look something like this;
calculate_remainder = lambda val1, val2: val1 % val2
Using Python’s modulus operator (that’s the percentage symbol %), our lambda function will return the remainder of val1 divided by val2. We would then be able to use this function with something like;
value = calculate_remainder(15, 7)
print(“The remainder of 15 divided by 7 is “, value)
This function would output the string, “The remained of 15 divided by 7 is 1”, simple. And you might have noticed that, while we can’t assign a function name like would with a regular function, we can assign an identifier to our function object. For comparison, the same functionality coded as a regular function would look like this;
def calculate_remainder(val1, val2):
return val1 % val2
What is the Benefit of Python Lambda Functions?
You might not be rushing out to find a good lambda tutorial yet, and we wouldn’t blame you. The above example illustrates how you can use a lambda function, but there’s no obvious benefit shown there. So let’s talk about why you might want to use lambda functions to improve code in your projects and grow your mastery over the python language.
Short Duration Functions
If you need a function but only for a short time—a function that gets used several times on initialization but not afterwards, for example—lambda is an excellent solution. Using this method, you can implement the convenience of a typical function without incurring the overheads of those functions. You can use it in regular functions to pass a function out as a result, which would look something like this;
return lambda val2: val2 * val1
lamdafunction = myfunction(10)
result = lambdafunction(3)
In the above code, the function would return a lambda function that can then be used to multiply one number by another. So, with the example we just gave, the lambda function would multiply a number by 10. We then set result to 30 by passing it the lambda function with a value of 3. It is also possible to use this kind of function multiple times within the program, as each call returns a unique lambda expression.
Filtering with the filter() Function
The filter() function, combined with a lambda function, allows you to easily filter through a list. In this usage, your lambda function would return a boolean value that signifies if an item is to be kept. The filter() function then returns a list of those items which returned true.
As an example of how this would work, consider the example below; we specify a simple list of numbers.
raw_data = [3, 4, 6, 7, 11, 14, 19, 25, 45, 49, 53, 68, 72] filtered_data = list(filter(lambda val: (val > 55), raw_data)) print(filtered_data) # [68, 72]
In that example, our lambda function helps filter() to determine which of the numbers in the list are greater than 55. The result would be a list containing only 68 and 72. It should be noted that only one iterable can be taken in as input, however.
Making Use of the map() Function
In a similar vein to filter(), the map() function allows you to apply expressions or operators to every item in a sequence, such as a list. As a rough example, if you had a list of numbers and you wanted to multiply each of them by 8, you could use map() and a lambda function to achieve that. That very example would look like this
list_of_numbers = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] modified_list = list(map(lambda val: val * 8, list_of_numbers)) print(modified_list) # [16, 32, 48, 64, 80, 96, 112, 128, 144, 160]
The resulting list would then contain all of the original numbers multiplied by 8 (16, 32, 48, etc.) and all nicely contained in a single line of code.
Functional Programming vs. Object-Oriented Programming
Python is an object-oriented programming language in which some elements of functional programming can be used. Lambda is one aspect of those functional programming components. It is difficult to adequately describe what the difference between the two is, but it can be boiled down to different approaches to the same goal. Object-oriented programming makes code easier to understand by sectioning out functional parts of the code into easily distinguishable parts. Functional programming makes code easier to understand by reducing the number of functional parts in the first place.
One of the key characteristics of functional programming is that the data is immutable. What this means in practical terms is that if, for example, you wanted to modify the values in a list, you would have to create a new list. You’ll notice that that’s precisely what happened in our above examples of both filter() and map(). We passed one list into the lambda function, but the output was an entirely different list. Another aspect of functional programming is that things are only computed when they are needed—you may see this referred to as “Laziness”.
Functional programming allows for the creation of “Pure Functions”, in which a function has no impact on the data or state, which has some advantages. One particular advantage is concurrency. Because the original data is never changed by a pure function, it is entirely threadsafe. Always a benefit when trying to optimize code on modern hardware where the number of threads at our disposal continues to rise with every new CPU brought to market.
Testing and Readability
Testing functional programming code is very easy. Calling a function will always return the same result (assuming you are handing it the same data), so as long you know what results to expect, you can quickly test your code to make sure it is behaving as it should.
On the readability front, there may be some disagreement. On the one hand, functional programming is far less verbose, making for cleaner looking code. On the other hand, things like lambda functions aren’t always intuitive in the way object-oriented code can be, and so it may not be immediately apparent what they are doing.
Which is Better?
As with many things in life, there is no clear and obvious “better” option between functional programming and object-oriented programming. The best tool for the job will vary depending on what the job is.
Python is largely an object-oriented programming language, so it makes sense that object-oriented code will be the first choice for many coders. But any programmer looking to make full use of the power of this programming language should not neglect Python lambda functions in their code. Once you understand functional programming, you will start to see situations where it can be useful.
Functionally, lambda functions won’t revolutionize your python code; you can’t do anything with them that you can’t do without them. But through using them, you can make your code more efficient, compact, and easier to read.
There will be times when using functional programming methods will make your life easier, such as manipulating data in a threaded environment. There will also be times when lambda functions are not the best tool for the job. Part of the path to becoming a well-rounded programmer is in knowing which of the tools at your disposal is best for the job.
Edited by: Stefan Bradstreet
About Stefan Bradstreet
Stefan is a Senior Software Developer at Amazon with 8+ years of experience in tech. He is passionate about helping people become better coders and climbing the ranks in their careers, as well as his own, through continued learning of leadership techniques and software best practices.
Thank you for visiting!
Please remember if you found this content useful and would like to see more python and software development articles from us, help us conquer the google algorithm in any of the ways below:
- Comment your thoughts below
- Share this on your social media
- follow me on twitter
- subscribe to our Youtube channel
- Contact me on the service page for coaching
- Shop through our affiliate links: Python crash course book
If you didn’t find what you expected feel free to use the contact page and let us know ways we can improve or what would help you grow as a developer better! I am honored by every view and it takes a village to really make this great.