
In order to understand how sorting by key works in the background, let's first see how sorted works when sorting lists of lists (or tuples). # Sort by population densityĬities = sorted(cities, key=lambda city: (city / city)) # Sort by country, then by nameĬities = sorted(cities, key=lambda city: (city, city))Ī nice trick with key function is that we can provide an arbitrary function that accepts an object to be sorted, for example we can calculate population density on the fly. As tuples are sorted by comparing them field by field, this will effectively sort our cities by country, then by name. Here, for each city we'll provide a tuple (country, name) to the sorting function. Sort alphabetically by country, then by name # Sort by populationĬities = sorted(cities, key=lambda city: city)Ī very common pattern is to reverse the sorting order by using negative value of the sorting key (note the minus sign in front of city) # Sort by population DESCENDINGĬities = sorted(cities, key=lambda city: -city)Ģ. This means that each city will be compared against other cities by looking only at their population field. We'll tell sorted that for each city, we want it to take population as the sorting key. Here's how we'd do this for our examples: We'll need to explicitly tell the sorted method how we want to sort our objects. What do you think happens if we just call sorted(dicts)? How will the sorted function know which field(s) of our cities to use for sorting? If there are cities from the same country order them alphabetically by nameįor the sake of example let's represent cities as simple Python dicts: cities = [

We'd like to sort the list in various ways: Let's say we have a list of city names along with their country, population and area. Sorting complex objects using a lambda key function

Here's an example: A = # An unsorted array of integersī = sorted(A) # sorted(A) returns a sorted copy of A It returns a sorted list of elements of that object. You'll pass a list, dict, set or any other kind of iterable object to the built-in function sorted.
