'Why doesn't lambda function accept parameter in bond with sorted()

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

sort_grades = lambda grades: grades[1]

Sorted_Students = sorted(Students,key=sort_grades)

lambda function kinda has a parameter grades. Why don't we pass any parameters in Sorted_Students as a key= so there is no parenthesis after sort_grades. And this code somehow works even without passing any parameters as "grades" so we don't even run the lambda function (how without parameters - imposible). Please detail how this code works the most explicitly, so my dumb brain could get something from your comment



Solution 1:[1]

To complete Tomer Ariel answer, functions in python might be passed as argument just as any object. An other function from the python standard library that uses this feature is map(). This function take an iterable and a function, and return a generator of the result of the function applied to each element of the iterable. A way it could be implemented :

def map(iterable, f): # Note : f is a function!
    return (f(i) for i in iterable) # and is indeed called

And could be use this way :

print(list(map([1,2,3,4,5], lambda x: x*x))) #we convert the generator to a list so it displays nicely
#it prints in the shell : [1,4,9,16,25]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TUI lover