Sorting a list of tuples in python according to an element index
Question: How can I sort a list of tuples according to the int in a certain position?
(without a for loop)

eg. Sorting `l = [(1,5,2),(7,1,4),(1,6,3)]` according to the third element in
each tuple?


Answer: You can use
[`list.sort`](http://docs.python.org/3/library/stdtypes.html#list.sort), its
key function, and
[`operator.itemgetter`](http://docs.python.org/3/library/operator.html#operator.itemgetter):

    
    
    >>> from operator import itemgetter
    >>> l = [(1,5,2),(7,1,4),(1,6,3)]
    >>> l.sort(key=itemgetter(2))
    >>> l
    [(1, 5, 2), (1, 6, 3), (7, 1, 4)]
    >>>
    

* * *

You could also use a [lambda
function](http://docs.python.org/3/tutorial/controlflow.html#lambda-
expressions) instead of `operator.itemgetter`:

    
    
    >>> l = [(1,5,2),(7,1,4),(1,6,3)]
    >>> l.sort(key=lambda x: x[2])
    >>> l
    [(1, 5, 2), (1, 6, 3), (7, 1, 4)]
    >>>
    

However, the latter is [generally
faster](http://stackoverflow.com/a/17243726/2555451).

