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?
You can use list.sort, its key function, and 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 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.
You can specify the key by which to sort a list using the sorted builtin:
>>> mylist = sorted([(1,5,2),(7,1,4),(1,6,3)], key = lambda t: t[2]) >>> mylist [(1, 5, 2), (1, 6, 3), (7, 1, 4)] >>>