Skip to main content

Sortying list of lists based on multiple criteria in Python [StackOverflow answer]

My answer to the following StackOverflow question: https://stackoverflow.com/questions/56556639/sorting-a-list-by-multiple-non-standard-criteria. They wanted to sort based on column 5, and then based on column 8, with entries that have value 0 being listed first.

If you use data.sort(key = lambda x:x[0] == 8), then it will sort every one with 8 on the position 0 to the last place. So what you could do would be the following:

First sort them, so all the 8 at the position 0 are on the end:

data.sort(key = lambda x:x[0] == 8)

Then sort based on the position 5:

data.sort(key = lambda x:x[5])

And then reverse the order:

data.reverse()