Skip to content

Python sort lambda | Example code

  • by

Use the list sort() method to sort a list with a lambda expression in Python. Just call the list.sort(key=None) with a 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])

print(data)

Output:

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:]))

print(res)

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)

print(res)

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

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

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.

Leave a Reply

Discover more from Tutorial

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

Continue reading