Estimated reading time: 3 minutes
Lambda functions are anonymous functions that take any amount of arguments as their input, but can only have one expression.
Let’s look at the function further
Lambda functions are anonymous and are usually classified as user-defined functions but without a name.
One thing that makes Lambda functions different from regular functions is that they do not have a return keyword in them.
Also typically Lambda functions may be used once and then never used again. You’ll often find regular functions are used many times within a program as they are doing a repetitive task.
So for example in a program, a regular function may be used to process a login attempt, and it is correct to approach it this way as that will be repeated many times over multiple users.
On the other hand, you may use a lambda function to check the no of attempts for a login, and then return the result to a regular function for processing. This example is one that is so random, and may not be used that often it requires just a check, and the result then can be used to decide on further steps.
Lambda functions should only be used to create simple expressions.
To give you an example expressions that do not include complex structures such as if-else, for-loops, and so on will be suitable for use with Lambda.
So what are examples of Lambda Functions?
In the below code, we are tracking the no of attempts for a person to try and log in to their account.
Essentially what is happening is that attempt_count would be a variable that changes as the no of attempts to log in goes up.
The whole idea here is that the variable attempt is changing using a Lambda function to monitor the no of attempts made:
attempt_count=3
attempt = (lambda x : x*1)(attempt_count)
print(attempt)
So if we want to say that at attempt 3 we want to suspend the user account we could add this code as follows:
# lambda that accepts one argument
attempt_count=3
attempt = (lambda x : x*1)(attempt_count)
print(attempt)
if attempt == 3:
print("Sorry your account is locked out")
What you will notice here is that the one Lambda function line is used to check the no of attempts and quickly identifies when a threshold is reached as defined by the owners of the system.
In the below, we are using a loop to check the same scenarios, and it is nine lines and very inefficient!
attempt_count=3
while attempt_count >=1:
if attempt_count == 1:
continue
elif attempt_count == 2:
continue
elif attempt_count == 3:
print("Sorry your account is locked out")
break
What are the benefits of using a Lambda function?
- It cuts down the code implementation and makes it more efficient as per the above.
- You won’t need to write a name for it, as in using “def” beforehand. As a result, you won’t accidentally call the function somewhere else in your code.
- You can apply filters quite easily with them.
- It keeps things simple as it is not used for complex situations, you put them in a proper function.