Sorting a list of tuples with 3 elements in python

list, python, sorting, tuples

Solution

Just sort the list; the default sort does just what you want.

When comparing two tuples, they are ordered according to their contents; sorted on the first element first, then if they are equal, sorted on the second element, etc.

Demo:

>>> L = [(14, 2, 3), (1, 14, 0), (14, 1, 1), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6)]
>>> sorted(L)
[(1, 14, 0), (1, 14, 2), (2, 4, 4), (4, 11, 5), (11, -1000, 6), (14, 1, 1), (14, 2, 3)]

I moved the `(14, 2, 3)` element forward to show that it is still sorted after `(14, 1, 1)`.

Python's `list.sort()` method and `sorted()` function take a `key` function that returns a value on which to sort instead if you need a different sort order. If you wanted to sort on the last element first, then second last, etc. for example, you'd use:

sorted(L, key=lambda t: t[::-1])

where the lambda returns a reversed tuple to sort on instead. The callable object you pass to `key` is called for each element in the input sequence to 'augment' the list before sorting, as if you had done:

[s[1] for s in sorted((key(s), s) for s in L)]

The `t[::-1]` uses a reversing slice.

For more detail, see the Python Sorting HOWTO.

Problem

I have a list of some tuples. Each tuple has three elements. I need to sort the list. To break tie between two tuples, first element of tuple is looked then if still tied then the second element. List is like below. ``` L = [(1, 14, 0), (14, 1, 1), (1, 14, 2), (14, 2, 3), (2, 4, 4), (4, 11, 5), (11, -1000, 6)] ``` In C the sort function takes a compare function and that does everything simply. But I couldn't figure it out after trying for sometimes in `python`. Can anybody help me?

Original source

Related problems