Easiest Way to Sort with Lambda in Python

In Python, the lambda keyword is used to create small anonymous functions. These functions can be used wherever a function is expected, such as in a call to the built-in sorted() function.

Here’s an example of how to use a lambda function with the sorted() function to sort a list of strings by their length:

words = ['apple', 'banana', 'cherry', 'date'] sorted_words = sorted(words, key=lambda x: len(x)) print(sorted_words)
Code language: Python (python)

This will output the following:

['date', 'apple', 'banana', 'cherry']
Code language: Python (python)

In this example, the sorted() function takes the words list as its first argument and a key argument that specifies a lambda function to be used as the sorting key. The lambda function takes a single argument x and returns the length of x, which is used by the sorted() function to determine the sort order.

You can also use a lambda function as the key argument when sorting a list of integers or floating-point numbers. For example:

numbers = [3, 1, 4, 2] sorted_numbers = sorted(numbers, key=lambda x: x) print(sorted_numbers)
Code language: Python (python)

This will output the following:

[1, 2, 3, 4]
Code language: JSON / JSON with Comments (json)

Sorting a List of Objects

Here’s an example of how to use a lambda function with the sorted() function to sort a list of objects based on one of their attributes:

class Student: def __init__(self, name, age, grade): self.name = name self.age = age self.grade = grade def __repr__(self): return f'{self.name} is {self.age} years old and has a grade of {self.grade}' students = [ Student('Alice', 16, 'A'), Student('Bob', 17, 'B'), Student('Charlie', 15, 'C'), Student('Dave', 16, 'D'), ] sorted_students = sorted(students, key=lambda x: x.grade) print(sorted_students)
Code language: Python (python)

This will output the following:

Alice is 16 years old and has a grade of A Bob is 17 years old and has a grade of B Charlie is 15 years old and has a grade of C Dave is 16 years old and has a grade of D
Code language: plaintext (plaintext)

In this example, the lambda function takes a single argument x (a Student object) and returns the value of its grade attribute, which is used by the sorted() function to determine the sort order.

One way to simplify the code above is to replace the lambda with the attrgetter() function from the operator module.

First, we need to import attrgetter:

from operator import attrgetter
Code language: Python (python)

Then, we can replace the lambda:

sorted_records = sorted(records, key=attrgetter('grade'))
Code language: Python (python)

Sorting a List of Dictionaries

Here’s an example of how to use a lambda function with the sorted() function to sort a list of dictionaries based on the value of a particular key:

records = [ {'name': 'Alice', 'age': 16, 'grade': 'A'}, {'name': 'Bob', 'age': 17, 'grade': 'B'}, {'name': 'Charlie', 'age': 15, 'grade': 'C'}, {'name': 'Dave', 'age': 16, 'grade': 'D'}, ] sorted_records = sorted(records, key=lambda x: x['grade']) print(sorted_records)
Code language: Python (python)

This will output the following:

[{'name': 'Alice', 'age': 16, 'grade': 'A'}, {'name': 'Bob', 'age': 17, 'grade': 'B'}, {'name': 'Charlie', 'age': 15, 'grade': 'C'}, {'name': 'Dave', 'age': 16, 'grade': 'D'}]
Code language: Python (python)

One way to simplify the code above is to replace the lambda with the itemgetter() function from the operator module.

First, we need to import itemgetter:

from operator import itemgetter
Code language: Python (python)

Then, we can replace the lambda with itemgetter:

sorted_records = sorted(records, key=itemgetter('grade'))
Code language: Python (python)

Final Notes

Finally, don’t forget that you can always add reverse=True to easily change the sort order when using sorted().

For example:

numbers = [3, 1, 4, 2] sorted_numbers = sorted(numbers, key=lambda x: x, reverse=True) print(sorted_numbers) # Output: [4, 3, 2, 1]
Code language: PHP (php)

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *