Lambda functions in Python are a powerful way to create small, anonymous functions on the fly. These functions are typically used for short, simple operations where the overhead of a full function definition would be unnecessary.
While traditional functions are defined using the def keyword, Lambda functions are defined using the lambda keyword and are directly integrated into lines of code. In particular, they are often used as arguments for built-in functions. They enable developers to write clean and readable code by eliminating the need for temporary function definitions.
In this article, we'll cover what Lambda functions do and their syntax. We'll also provide some examples and best practices for using them, and discuss their pros and cons.
Lambda functions have been a part of Python since version 2.0, so you'll need:
In this tutorial, we'll see how to use Lambda functions with the library Pandas: a fast, powerful, flexible, and easy-to-use open-source data analysis and manipulation library. If you don't have it installed, run the following:
pip install pandas
First, let's define the syntax developers must use to create Lambda functions.
A Lambda function is defined using the lambda keyword, followed by one or more arguments and an expression:
lambda arguments: expression
Let's imagine we want to create a Lambda function that adds up two numbers:
add = lambda x, y: x y
Run the following:
result = add(3, 5) print(result)
This results in:
8
We've created an anonymous function that takes two arguments, x and y. Unlike traditional functions, Lambda functions don't have a name: that's why we say they are "anonymous."
Also, we don't use the return statement, as we do in regular Python functions. So we can use the Lambda function at will: it can be printed (as we did in this case), stored in a variable, etc.
Now let's see some common use cases for Lambda functions.
Lambda functions are particularly used in situations where we need a temporarily simple function. In particular, they are commonly used as arguments for higher-order functions.
Let's see some practical examples.
map() is a built-in function that applies a given function to each item of an iterable and returns a map object with the results.
For example, let's say we want to calculate the square roots of each number in a list. We could use a Lambda function like so:
# Define the list of numbers numbers = [1, 2, 3, 4] # Calculate square values and print results squared = list(map(lambda x: x ** 2, numbers)) print(squared)
This results in:
[1, 4, 9, 16]
We now have a list containing the square roots of the initial numbers.
As we can see, this greatly simplifies processes to use functions on the fly that don't need to be reused later.
Now, suppose we have a list of numbers and want to filter even numbers.
We can use a Lambda function as follows:
# Create a list of numbers numbers = [1, 2, 3, 4] # Filter for even numbers and print results even = list(filter(lambda x: x % 2 == 0, numbers)) print(even)
This results in:
[2,4]
The sorted() function in Python returns a new sorted list from the elements of any iterable. Using Lambda functions, we can apply specific filtering criteria to these lists.
For example, suppose we have a list of points in two dimensions: (x,y). We want to create a list that orders the y values incrementally.
We can do it like so:
# Creates a list of points points = [(1, 2), (3, 1), (5, -1)] # Sort the points and print points_sorted = sorted(points, key=lambda point: point[1]) print(points_sorted)
And we get:
[(5, -1), (3, 1), (1, 2)]
Given their conciseness, Lambda functions can be embedded in list comprehensions for on-the-fly computations.
Suppose we have a list of numbers. We want to:
Here's how we can do that:
# Create a list of numbers numbers = [1, 2, 3, 4] # Calculate and print the double of each one squared = [(lambda x: x ** 2)(x) for x in numbers] print(squared)
And we obtain:
[1, 4, 9, 16]
Given the examples we've explored, let's run through some advantages of using Lambda functions:
Let's briefly discuss some limitations and drawbacks of Lambda functions in Python:
Now that we've considered some pros and cons, let's define some best practices for using Lambda functions effectively:
In certain cases, more advanced Lambda function techniques can be of help.
Let's see some examples.
Lambda functions can be nested for complex operations.
This technique is useful in scenarios where you need to have multiple small transformations in a sequence.
For example, suppose you want to create a function that calculates the square root of a number and then adds 1. Here's how you can use Lambda functions to do so:
# Create a nested lambda function nested_lambda = lambda x: (lambda y: y ** 2)(x) 1 # Print the result for the value 3 print(nested_lambda(3))
You get:
10
Many Python libraries leverage Lambda functions to simplify complex data processing tasks.
For example, Lambda functions can be used with Pandas and NumPy to simplify data manipulation and transformation.
Suppose we have a data frame with two columns. We want to create another column that is the sum of the other two. In this case, we can use Lambda functions as follows:
# Create the columns' data data = {'A': [1, 2, 3], 'B': [4, 5, 6]} # Create data frame df = pd.DataFrame(data) # Create row C as A B and print the dataframe df['C'] = df.apply(lambda row: row['A'] row['B'], axis=1) print(df)
And we get:
A B C 0 1 4 5 1 2 5 7 2 3 6 9
That's it for our whistle-stop tour of Lambda functions in Python!
In this article, we've seen how to use Lambda functions in Python, explored their pros and cons, some best practices, and touched on a couple of advanced use cases.
Happy coding!
P.S. If you'd like to read Python posts as soon as they get off the press, subscribe to our Python Wizardry newsletter and never miss a single post!
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3