What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Sort with Lambda in Python | 7 Methods (With Code)

  • Sep 15, 2023
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Abhisek Ganguly
How to Sort with Lambda in Python | 7 Methods (With Code)

Python offers a variety of tools and techniques when it comes to sorting data. Among them, the use of lambda functions in sorting is a powerful and flexible approach. In this article, we will delve into the world of Python sorting with lambda and explore different types of problems where sorting plays a crucial role.

What is a Lambda Function in Python?

A lambda function, also known as an anonymous function, is a small, nameless function defined using the lambda keyword. Lambda functions can take any number of arguments but can only have one expression. They are commonly used for short, simple operations.

Lambda is commonly used in Python with the `sorted()` function for custom sorting.

Here's the basic syntax of a lambda function:

lambda arguments: expression

 

Now that we have a basic understanding of lambda functions, let's explore various problems where sorting with lambda can be a valuable solution.

Problem 1: Sorting a List of Strings by Length

Imagine you have a list of strings, and you want to sort them by their lengths in ascending order. This is a common task in text processing or natural language processing.

words = ["apple", "banana", "cherry", "date", "elderberry"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)

 

Output:

['date', 'apple', 'cherry', 'banana', 'elderberry']

 

In this code, the `sorted()` function is used with a lambda function as the `key` argument. The lambda function takes each word `x` from the list and returns its length, which is used for sorting.

Problem 2: Sorting a List of Dictionaries by a Specific Key

Suppose you have a list of dictionaries, each representing a person with attributes like name and age. You want to sort this list of dictionaries by a specific key, such as age.

people = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 20},
]

sorted_people = sorted(people, key=lambda x: x["age"])
print(sorted_people)

 

Output:

[{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

 

In this code, the `sorted()` function is used with a lambda function as the `key` argument to sort the list of dictionaries based on the "age" key.

Problem 3: Sorting a List of Tuples by Multiple Criteria

Sometimes, you may need to sort a list of tuples by multiple criteria. For example, you may want to sort a list of students' records by their names in ascending order and, for students with the same name, by their scores in descending order.

students = [("Alice", 85), ("Bob", 92), ("Alice", 78), ("Charlie", 92)]

sorted_students = sorted(students, key=lambda x: (x[0], -x[1]))
print(sorted_students)

 

Output:

[('Alice', 78), ('Alice', 85), ('Bob', 92), ('Charlie', 92)]

 

Here, the lambda function takes a tuple `x` and returns a tuple `(x[0], -x[1])` as the key. The negative sign is used to sort the scores in descending order.

Problem 4: Sorting a List of Custom Objects

When working with custom objects, you can use lambda functions to define custom sorting criteria for those objects.

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

students = [
    Student("Alice", 25),
    Student("Bob", 20),
    Student("Charlie", 30),
]

sorted_students = sorted(students, key=lambda x: x.age)
for student in sorted_students:
    print(f"{student.name}: {student.age}")

 

Output:

Bob: 20
Alice: 25
Charlie: 30

 

In this code, we define a `Student` class and sort a list of `Student` objects based on their ages using a lambda function.

Problem 5: Sorting a List of Complex Data Structures

In some cases, you may need to sort a list of more complex data structures, like a list of lists with various attributes.

data = [
    [3, "apple", 12.5],
    [1, "banana", 10.0],
    [2, "cherry", 15.0],
]

sorted_data = sorted(data, key=lambda x: (x[2], x[0]))
for item in sorted_data:
    print(item)

 

Output:

[1, 'banana', 10.0]
[3, 'apple', 12.5]
[2, 'cherry', 15.0]

 

Here, we sort the list `data` based on the third element (index 2) and, in the case of ties, based on the first element (index 0) of each sublist.

Problem 6: Sorting a List of Objects with Custom Comparison Logic

In some scenarios, you may need to sort objects with complex comparison logic. You can define a custom comparison function using a lambda function for this purpose.

class Product:
    def __init__(self, name, price, rating):
        self.name = name
        self.price = price
        self.rating = rating

products = [
    Product("Laptop", 1000, 4.5),
    Product("Phone", 800, 4.8),
    Product("Tablet", 500, 4.2),
]

sorted_products = sorted(products, key=lambda x: (x.rating, -x.price))
for product in sorted_products:
    print(f"{product.name}: Price ${product.price}, Rating {product.rating}")

 

Output:

Tablet: Price $500, Rating 4.2
Laptop: Price $1000, Rating 4.5
Phone: Price $800, Rating 4.8

 

In this code, we sort a list of `Product` objects based on their ratings in ascending order and, in the case of ties, based on their prices in descending order.

Problem 7: Sorting with Reverse Order

By default, the `sorted()` function sorts in ascending order. You can use a lambda function to reverse the sorting order.

numbers = [5, 2, 9, 1, 5, 6]

sorted_descending = sorted(numbers, key=lambda x: x, reverse=True)
print(sorted_descending)

 

Output:

[9, 6, 5, 5, 2, 1]

 

In this code, the lambda function `lambda x: x` returns the same value, effectively sorting the numbers in descending order when `reverse=True` is set.

Conclusion

In this article, we've explored several practical examples of sorting problems and how to solve them using lambda functions. Python's lambda functions provide a flexible way to define custom sorting criteria for various data structures, from simple lists to complex objects. By leveraging lambda functions in conjunction with the `sorted()` function, you can efficiently tackle a wide range of sorting challenges in Python.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abhisek Ganguly
Passionate machine learning enthusiast with a deep love for computer science, dedicated to pushing the boundaries of AI through academic research and sharing knowledge through teaching.