6
lst = [(1,(1,3,5)), (5,(2,3,4)),(3,(2,3,4))]

I want to sort by the first value, descending order.

5 Answers 5

12

just like this:

sorted(lst, reverse=True)
Sign up to request clarification or add additional context in comments.

2 Comments

to every other answerer: the index is not required. Python always sorts lists by the first element it finds.
actually, Python compares tuples by lexicographic order, so it does not only sort lists/tuples by their first elements. This distinction is important if a "stable" sorting by first element is desired.
6

Sort in place? Use:

lst.sort(reverse=True)

Comments

4
import operator
sorted(lst, reverse=True, key=operator.itemgetter(0))

Comments

0
sorted(list, reverse=True, key=lambda x: x[0])

Note also that "list" isn't a great name for your list because it's the built-in list type.

Comments

0

You can sort like this.

sorted(lst, key=lambda a: a[0], reverse=True)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.