Using sorted() to put data in order
When we need to produce results in a defined order, Python gives us two choices. We can create a list
object and use the list.sort()
method to put items in an order. An alternative is to use the sorted()
function. This function works with any iterable, but it creates a final list
object as part of the sorting operation.
The sorted()
function can be used in two ways. It can be simply applied to collections. It can also be used as a higher-order function using the key=
argument.
Let's say we have our trip data from the examples in Chapter 4, Working with Collections. We have a function that will generate a sequence of tuples with start, end, and distance for each leg
of a trip
. The data looks as follows:
( ((37.54901619777347, -76.33029518659048), (37.840832, -76.273834), 17.7246), ((37.840832, -76.273834), (38.331501, -76.459503), 30.7382), ((38.331501, -76.459503), (38.845501, -76.537331), 31.0756), ((36.843334, -76.298668), (37.549, -76.331169), 42...