sorting a list of tuples in Python

python

Solution

That pattern is called decorate-sort-undecorate.

- You turn each `(1, 3)` into `(3, (1, 3))`, wrapping each `tuple` in a new tuple, with the item you want to sort by first.

- You sort, with the outer `tuple` ensuring that the second item in the original `tuple` is sorted on first.

- You go back from `(3, (1, 3))` to `(1, 3)` while maintaining the order of the list.

In Python, explicitly decorating is almost always unnecessary. Instead, use the `key` argument of `sorted`:

sorted(list_of_tuples, key=lambda tup: tup[1]) # or key=operator.itemgetter(1)

Or, if you want to sort on the reversed version of the `tuple`, no matter its length:

sorted(list_of_tuples, key=lambda tup: tup[::-1]) 
                              # or key=operator.itemgetter(slice(None, None, -1))

Problem

While working on a problem from Google Python class, I formulated following result by using 2-3 examples from Stack overflow- ``` def sort_last(tuples): return [b for a,b in sorted((tup[1], tup) for tup in tuples)] print sort_last([(1, 3), (3, 2), (2, 1)]) ``` I learned List comprehension yesterday, so know a little about list comprehension but I am confused how this solution is working overall. Please help me to understand this (2nd line in function).

Original source