Skip to content

Python sorted lambda

  • by

Use sorted() function for simple data but complex objects using a lambda key function in Python. We can also add reverse=True, after the sorting condition, to sort the elements in reverse order.

sorted(a, key=lambda x: x.modified, reverse=True)

Take a look at this Example, you will understand:

a = ["tim", "bob", "anna", "steve", "john","aaaaa","zzza"]
a = sorted(a, key = lambda x:(x[-1],len(x),x))

Python sorted lambda example

Simple example code sorted data for the city, compared against other cities by looking only at their population field.

cities = [
        "name": "New York",
        "country": "USA",
        "population": 20.14,

        "name": "Tokyo",
        "country": "Japan",
        "population": 37.47,

        "name": "Los Angeles",
        "country": "USA",
        "population": 13.2,

        "name": "Madrid",
        "country": "Spain",
        "population": 6.79,

        "name": "Osaka",
        "country": "Japan",
        "population": 19.3,

        "name": "London",
        "country": "United Kingdom",
        "population": 14.26,

# Sort by population
cities = sorted(cities, key=lambda city: city['population'])

# Sort by population DESCENDING
cities = sorted(cities, key=lambda city: -city['population'])


Python sorted lambda example

Sort the list according to the column using lambda

def sortArr(arr):
    for i in range(len(array[0])):
        res = sorted(arr, key=lambda x: x[i])

        print(i, res)

array = [['java', 1995],
         ['c++', 1983],
         ['python', 1989]]



0 [['c++', 1983], ['java', 1995], ['python', 1989]]
1 [['c++', 1983], ['python', 1989], ['java', 1995]]

Sort a list of strings using lambda and with multiple conditions

a = ["AAd", "aAAd", "AAAd", "adAA"]
a.sort(key=lambda x: (len(x), -x.count('A')))

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

IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
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