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) print(fruits)
How to use a lambda expression with the
# 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) print(people)
In this example, the lambda expression
lambda person: person 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
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35), ("David", 28)] sorted_people = sorted(people, key=lambda person: person) 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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.