0

What I am trying to do is sort a list of tuples, that the first cell in the tuple can be many nested tuples, but the second cell is always a int value,

My code:

t = [('d',2), ('b', 1), (('a', 'c'), 2)]
sorted(t, key=lambda x: x[1], reverse=True)

But this is not working, the last nested tuple stays in the end. any ideas?

5
  • I cannot reproduce your issue; I get [('d', 2), (('a', 'c'), 2), ('b', 1)]. Or did you expect (('a', 'c'), 2) to be sorted first? Commented Jan 2, 2014 at 18:30
  • 2
    What order do you want those three items to end up in? Commented Jan 2, 2014 at 18:31
  • i am getting ('d', 2), ('b',1)..... Commented Jan 2, 2014 at 18:33
  • 2
    And note that sorted() returns a new, sorted list. If you wanted t to be sorted in-place, call t.sort() instead. Commented Jan 2, 2014 at 18:33
  • that was the issue, sort and not sorted(), i didn't understand why the list wont change! Commented Jan 2, 2014 at 18:36

1 Answer 1

4

The sorted method return a new sorted list. It does not modify the existing list. On the other hand, list.sort() method sort the list in-place.

t = [('d',2), ('b', 1), (('a', 'c'), 2)]

To sort this use either

t = sorted(t, key=lambda x: x[1], reverse=True)

or

t.sort(t, key=lambda x: x[1], reverse=True)
Sign up to request clarification or add additional context in comments.

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.