How to Sort With Lambda in Python

Sorting data in Python can be done in multiple ways.

In this article, we will be focusing on sorting data using the Lambda function in Python.

The Lambda function is a small anonymous function that is used to perform a single expression of operation.

In Python, the sorting function can be used with the help of the “sorted()” method.

This method can take a few parameters, one of which is the “key” parameter, which we will be using to sort our data using the Lambda function.


What is the Lambda Function in Python?

The Lambda function in Python is a small anonymous function that is used to perform a single expression of operation.

The function is defined using the “lambda” keyword, followed by the parameters, a colon, and then the expression that needs to be executed.

The syntax of the Lambda function in Python is as follows:

lambda arguments : expression

Sorting data using the Lambda function

To sort data using the Lambda function in Python, we will be using the “sorted()” method and passing the “key” parameter as the Lambda function.

The “key” parameter is used to specify a custom sorting key, which will be used to sort the data.

Let’s take a look at an example to understand this better.

Suppose we have a list of tuples, where each tuple contains a name and an age. We want to sort this list of tuples based on the age of the individuals.

Here is the code to sort the data using the Lambda function in Python:

List of tuples
data = [(“John”, 25), (“Jane”, 22), (“Jim”, 30), (“Jill”, 28)]

Sorting the data based on age using Lambda function
sorted_data = sorted(data, key=lambda x: x[1])

print(“Sorted data based on age:”, sorted_data)

The output of the above code will be:

Sorted data based on age: [(‘Jane’, 22), (‘John’, 25), (‘Jill’, 28), (‘Jim’, 30)]

As you can see, the data is sorted based on the age of the individuals.

The “key” parameter in the “sorted()” method is set to the Lambda function, which takes a tuple as input and returns the second element (age) of the tuple.


Conclusion

In this article, we learned about the Lambda function in Python and how to sort data using the Lambda function in Python.

The Lambda function is a small anonymous function that is used to perform a single expression of operation.

The “sorted()” method in Python can be used to sort data, and the “key” parameter can be used to specify a custom sorting key, which can be the Lambda function.