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

Time:05-20

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

CodePudding user response:

The key parameter of sorted is a function which will be applied to the elements in order to compare them to each other. Therefore, we only pass the function itself without calling it.

I suggest you read the documentation first next time :) https://docs.python.org/3/library/functions.html#sorted

CodePudding user response:

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]
  • Related