I look at someone else's code, and I don’t know what this function is, or rather its 2nd line, where you can read about such constructions? And how does it work?

def get_biggest_bar(bars): result = max(bars, key=lambda tmp: tmp.get("SeatsCount", float('inf'))) return result['Name'] 

3 answers 3

lambda functions are a simplification for programmers — instead of writing a separate function for a single expression, you can use the single-line version, which is immediately passed as an object.

Example:

 >>> x = lambda y: y*2 >>> x(2) 4 

You do not need to use return .

In your case, the lambda function is passed as the key argument to the max function, which receives an analog of this function:

 def f(tmp): return tmp.get("SeatsCount", float('inf')) 

    Anonymous functions have a default built-in return - this means that anonymous functions work only with expressions that return data.

    Anonymous functions have no names (except for the definition in a variable) and it starts with the reserved word lambda .

     print (lambda x,y: x*y)(10,20) print (lambda x: True if x % 2 == 0 else False)(10) 

    4.7.5. Lambda expressions

      The lambda x: x*x expression lambda x: x*x creates an anonymous function that behaves like:

       def <lambda>(x): return x*x 

      The types of functions created are exactly the same, the only difference is in the presence / absence of the name and the restriction on the code to one expression inside lambda.

       >>> print(*range(-10, 0)) -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 >>> max(range(-10, 0)) -1 >>> max(range(-10, 0), key=lambda x: x*x) -10 >>> def square(x): ... return x*x ... >>> max(range(-10, 0), key=square) -10