Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand lambda usage in given python code

Tags:

python

lambda

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]
like image 471
mtk Avatar asked Jun 30 '14 08:06

mtk


People also ask

How do you read lambda in Python?

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).

What is the use of lambda function in python explain with example?

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.

What is lambda function in Python Support your answer with appropriate code?

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.

What is the lambda function in python utilized for?

Lambda functions reduce the number of lines of code when compared to normal python function defined using def keyword.


1 Answers

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.

like image 174
Jasper Avatar answered Oct 20 '22 21:10

Jasper