Sort complex objects by index

Here’s a quick and elegant way to sort complex objects in Python (for instance, a list of lists or a 2D array), using the objects’ indices as the key. Sorting by the second column:

Input:

data = [ [5, 7, 3],
         [4, 2, 2],
         [0, 3, 5],
       ]

Code:

data = sorted(data, key=lambda x: x[1])

The lambda keyword lets us define a mini-function which receives x (in this case, our row) and returns the second element of x (x[1]).

Output:

[[4, 2, 2],
 [0, 3, 5],
 [5, 7, 3]]