On reading through some code, I came across the below snippet which I am not able to understand. Would anyone be able to guide/provide hints/link or a basic explanation of line 3 below
def do_store(*args, **kwargs):
try:
key = (args, tuple(sorted(kwargs.items(), key=lambda i:i[0])))
results = f._results
mainly, what is the following doing?
key=lambda i:i[0]
Syntax. Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).
In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.
Python Lambda Functions are anonymous function means that the function is without a name. As we already know that the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python.
Lambda functions reduce the number of lines of code when compared to normal python function defined using def keyword.
With the lambda
keyword, you create "anonymous functions". They don't have (and don't need to have) a name, because they are immediately assigned (usually) to a callback function.
lambda i:i[0]
is just the body of the function
def f(i):
return i[0]
The key
parameter of the sorted
function has to be a function that computes sorting key for a given item. You could also pass the function (name) f
as defined above, or use a lambda
function for better readability.
As stated in tobias_k's answer, in this piece of code, the whole key
parameter is useless.
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