Have you ever wished you could write code without having to name your function or variable? Well, with python, you can. Python lambda function let you write code in a way that keeps your identity hidden. This makes it perfect for code that must be protected from disclosure, such as code that handles sensitive data or interacts with external systems.
This nifty little function in Python allows you to execute a code block without providing the function’s name or the variable that will hold the result. This can be very useful when you do not want to reveal the details of your code or do not want to clutter up your code with unnecessary information. In this article, we will show you how to create and use Python lambda function. Let us look at few examples to understand better how this works.
Table of Contents
What is Python Lambda Function?
An lambda function is a nameless function , and it can be used to hide the source of code from other users. This makes it an ideal solution for situations where you do not want your code to be visible to others or when you do not want to reveal the internal workings of your program.
Python Lambda Function is also known as Anonymous Function. Anonymous functions are also helpful for generating complex or customized logic without writing long lines of coding. For example, you can sequence different operations using lambda/anonymous functions without specifying their order beforehand. Additionally, they allow callbacks in Python with more flexibility than traditional methods.
How to use in Python ?
In Python, lambda functions are a particular type that does not have a name. For example, you cannot use parentheses to specify which function should be called – the keyword “anonymous” is automatically inserted for you because it is a single expression function.
Python anonymous function can be implemented by using the following lambda expression along with the lambda keyword.
lambda arg1, arg2, ... argN: expression
1. Using Lambda Function with filter()
Lambda filter() is a function that takes an input and produces the output as a list. The first parameter to filter() is the value you want to extract from the list, while the second argument is the input for which you want to create a filtered version of that list.
To understand this consider the following code example. First, we input an array as the first parameter, then apply the lambda filter function to extract values greater than 4.
array = [1,5,9,8,7,6,2,4] filtered_result = filter (lambda x: x > 4, array) print(list(filtered_result))
2. Using Lambda Function with map()
Python’s map function accepts a function and a list as inputs. Then, it returns a new list that includes all the lambda-changed items returned by the respective function for each item.
In the following code example, we use The map function to take square of each items in a list.
array = [1,5,9,8,7,6,2,4] filtered_result = map (lambda x: x*x, array) print(list(filtered_result))
3. Python Lambda with Reduce Function
Reduce function is a Python standard library function that returns a single value by processing an arbitrary amount of arguments. two arguments, the first of which is a list or array and the second of which is an operation to be performed on it.
To get better understanding consider the following code example,
from functools import reduce from numpy import subtract array = [1,8,3,9,5] subtract = reduce (lambda x, y: x-y, array) print(subtract)
4. Python Lambda Function to Return Cube
Lambda functions are famous for their clean and simple syntax, making them perfect for tasks that need to be repeated regularly. For example, def is a built-in function in Python that allows you to define a function within a given namespace.
In the following code snippet, we use the lambda function () to calculate the cube of a given number
# cube of given number lambda_cube = lambda x: x*x*x print(lambda_cube(8))
5. Python Lambda Function with List Comprehension
List comprehension is a simple way of storing data in Python that can be used to generate lists automatically. It works by taking an input list and generating a new list containing the elements of the original list. This makes it perfect for working with large datasets or processing repeated tasks quickly.
List comprehensions are also versatile, so you can use them for various purposes, such as extracting specific values from a data set, counting items, or finding duplicate entries.
Let us consider the following code example to understand how list comprehension works with lambda function.
tables = [lambda x=x: x*6 for x in range(1, 6)] for table in tables: print(table())
6. Python Lambda Function with if-else
Python Lambda Function with if-else can be used to simulate a decision making process. It takes two input parameters, called “condition” and “action”, and returns either True or False depending on whether the condition is satisfied or not.
In the below code snippet, we use max function to print the greatest number
Max = lambda x, y : x if(x > y) else y print(Max(1, 4))
What are the major limitations of lambda function?
The default timeout is 3 seconds, and the maximum time a function may run is 15 minutes; therefore, Lambda is unsuitable for lengthy-running workloads.
What is the benefit of lambda?
In Python, the lambda operator is a quick way of creating tiny unnamed functions. Like any other simple functions declared with the def keyword, Lambda functions behave in the same way. When function objects are needed, they can be used.
Does lamba function contain multiple statements?
Regular functions can have multiple expressions and statements however in lambda function we can construct two lambda functions and then pass the second one as a parameter to the first lambda function, despite the fact that they do not allow multiple statements.
In this article, we have explained the key factors of Python lambda function and different methods. Writing anonymous functions helps you keep your code neat and organized. It is also called a standard function. We hope this guide has helped you gain new knowledge about the Python anonymous/lambda function. Thanks for reading.