Python sort lambda | Example code

Use the list sort() method to sorting a list with a lambda expression in Python. Just call list.sort(key=None) with key set to a lambda expression to sort the elements of the list by the key.

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 sort lambda in Python

Simple example code, sorting the data by index value 0.

data = [("B", 5, "20"), ("A", 1, "5"), ("C", 6, "10")]
data.sort(key=lambda x: x[0])



Python sort lambda

Another example with the sorted() method

Here is code to sort through its “integers”.

ids = ['id5', 'id1', 'id2', 'id5', 'id4', 'id3']

res = sorted(ids, key=lambda x: int(x[2:]))


Output: [‘id1’, ‘id2’, ‘id3’, ‘id4’, ‘id5’, ‘id5’]

Revere sort the list using lambda

ids = [5, 2, 3, 1, 4]

res = sorted(ids, key=lambda x: x, reverse=True)


Output: [5, 4, 3, 2, 1]

Do comment if you have any doubts and suggestions on this Python lambda tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.