I’m learning about lambdas in Python, but I don’t understand what’s going on in this example.
Can anyone explain what's going on here in plain English? The example says it's “passing a small function as an argument”, but I don’t understand what that means.
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Lambda functions may be implemented as closures, but they are not closures themselves. This really depends on the context in which you use your application and the environment. When you are creating a lambda function that uses non-local variables, it must be implemented as a closure.
a function that can be treated as an object is just a delegate. What makes a lambda a closure is that it captures its outer variables. lambda expressions converted to expression trees also have closure semantics, interestingly enough.
Creating a Lambda FunctionThe lambda operator cannot have any statements and it returns a function object that we can assign to any variable. For example: remainder = lambda num: num % 2 print(remainder(5)) Output 1. In this code the lambda num: num % 2 is the lambda function.
You organize your code into Lambda functions. Lambda runs your function only when needed and scales automatically, from a few requests per day to thousands per second. You pay only for the compute time that you consume—there is no charge when your code is not running.
You're using a lambda expression (or anonymous function), to sort
your list of tuples based on a certain key
. pair[1]
indicates that you are sorting with a key of the elements in the index position of 1 in each tuple (the strings). Sorting with strings sorts by alphabetical order, which results in the output you are seeing.
Were you to use the first element in each tuple as the sorting key
for instance (pair[0]
), you would then sort in increasing numerical order:
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[0])
>>> pairs
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With