Sorting list of list by multiple columns

Hi!

I decided to spend some time in Practice mode and have to say that it´s been a very good decision. I had to reread the documentation of many functions and methods that I thought I knew everything about them, but it resulted that there´s always something new to learn.

So, my question is related to this mission: https://app.dataquest.io/m/1018/lists/20/sorting-lists-of-lists-ii

I´ve come out with the following solution:

def sort_index(a_list):
    a_list.sort()
    a_list.sort(key=lambda student: student[2], reverse=True)

And tried it with a sample list grades.

It worked as expected: the students were sorted by their grades in descending order while in alphabetical order of names inside each grade group.

But my answer wasn´t accepted by the answer checking machine.

The solution sorts for the first time also using the key argument:

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

although in my opinion when no key is passed the default sort should work by the first character of inner lists and if so, both solutions work identically. Could there be some specific cases when the output won´t be identical? Or, is it just the way the answer checking machine works and my answer is also correct?

Your sort will sort more than just the 1st character. If 1st character ties, it will also sort based on 2nd and so on. The solution does not do that. If the input ties in 3rd character, then also ties in 1st character, then has 2nd character out of order, your code will sort it, solution will not, hence a different result.

Did you think deep about why in this exercise, the 1st char was sorted first and not the 3rd char first?
Here you can think about the concept of a stable sort. Python has many more examples on sorting that are useful to know if you want to do data analytics accurately. https://docs.python.org/3/howto/sorting.html#:~:text=The%20sort%20is%20stable%20–%20if,most%20the%20first%20two%20items.

Thank you!

That´s what I needed.

Yes, I did. What I did not was to think in deep how sorting without passing any key parameter works, and you explained it earlier.