-1

I'm doing some practice on Dataquest.

Here's the exercise:

Create a function, sort, that:

  • Takes as input a list of lists.
  • Orders the outer list by the third element in the inner lists in descending order.
  • Resolves ties by sorting by the first one in ascending order.
  • Modifies the input in place..

What I've done:

def sort_index(some_list):
    some_list.sort(key=lambda x: x[2], reverse=True)
    some_list.sort(key=lambda x: x[0])

The output:

  • Function sort_index did not correctly modify the value of argument number 1.

Can someone explain to me why it worked when I reversed lines 1 and 2:

def sort_index(some_list):
    some_list.sort(key=lambda x: x[0])
    some_list.sort(key=lambda x: x[2], reverse=True)
lyapore
  • 7
  • 2

1 Answers1

0

The first .sort call is not needed, only the second one (with x[2]) matters if there are no ties. The only remaining behavior to understand is what happens to ties.

The list .sort method in Python is a stable sort, that's needed for it to work.

For example, if your input contains ('a', None, 5) and ('b', None, 5) tied on x[2], then the first .sort call will put them in this order (relative to each other) because 'a' < 'b', and the second .sort call will keep this order, because 5 == 5 and the sort is stable.

pts
  • 80,836
  • 20
  • 110
  • 183