Skip to content

Python list sort lambda expression | Example code

Use the list sort() method to sort with a lambda expression in Python. Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons.

Example of how to sort with lambda in Python

Simple example code Call list sort with a key set to a lambda expression to sort the elements of a list by the key.

fruits = [("Apples", 5, "20"), ("Pears", 1, "5"), ("Oranges", 6, "10")]

fruits.sort(key=lambda x: x[0])

print(fruits)

Output:

Python list sort lambda expression

Another example

How to use a lambda expression with the sort() method:

# List of tuples (name, age)
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35), ("David", 28)]

# Sorting by age using a lambda expression
people.sort(key=lambda person: person[1])

print(people)

In this example, the lambda expression lambda person: person[1] is used as the key function for sorting. It extracts the second element of each tuple (age) and uses it as the basis for sorting.

Keep in mind that the sort() method sorts the list in-place and doesn’t create a new list. If you want to create a new sorted list without modifying the original list, you can use the sorted() function with the same key parameter:

people = [("Alice", 30), ("Bob", 25), ("Charlie", 35), ("David", 28)]

sorted_people = sorted(people, key=lambda person: person[1])

print(sorted_people)

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

1 thought on “Python list sort lambda expression | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading