Search code examples
pythonsortingkey

Why key parameters in Python has to be "so complicated"?


This code is from Bro Code Python Course

students = (("Squidward", "F", 60),
            ("Sandy", "A", 33),
            ("Patrick", "D", 36),
            ("Spongebob", "B", 20),
            ("Mr. Krabs", "C", 78))

age = lambda ages: ages[2]
sorted_students = sorted(students, key=age)

for i in sorted_students:
    print(i)

I wonder why "key" has to have "so complicated" syntax

What is ages and ages[2] anyway? How does python know that I was referring to the index in the tuple?

In short, I completely don't understand the concept of key=age where age is memory address of ages[2]

I tried it solve like

age = 2
sorted_students = sorted(students, key=age)

or just

sorted_students = sorted(students, key=2)

Solution

  • The key parameter is a function. Named lambdas are considered bad style because, as you point out, they’re confusing-looking. If you’re going to name it, use a def, and use names that make it more clear what the function is doing.

    Eg replace this:

    age = lambda ages: ages[2]
    sorted_students = sorted(students, key=age)
    

    with this:

    def get_age(student):
        return student[2]
    
    sorted_students = sorted(students, key=get_age)
    

    and hopefully the way key is working will seem less mysterious.