0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)] >>> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.