Oct-16-2020, 07:30 PM
(Oct-16-2020, 12:46 PM)Drone4four Wrote: W3schools has a tutorial on lambdas which uses this example:
def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11))
I think the way they've written this example adds to your confusion. There's no need to use a lambda here; it's just an unnecessary extra level of indirection.
It's better to see passing a function to another where it actually makes sense to do so. In the case of
sorted
, as you've seen, it allows you to customise the way the sorting is done. Other examples are map
which allows you to transform each of the elements in an iterable, where the function you pass specifies how to transform an element; or filter
, where the function you pass allows you to define which items to keep:>>> names = ["Kernighan", "Ritchie", "Thompson"] >>> list(map(lambda name: name.upper(), names)) ['KERNIGHAN', 'RITCHIE', 'THOMPSON']
>>> values = [1, 2, 3, 4, 5] >>> list(filter(lambda x: x % 2 == 0, values)) [2, 4]Of course, you could do the same with list comprehensions here.