Oct-16-2020, 12:46 PM
Working on CodeChallenges’ PyBite #5, here is the list I am working with:
What I don’t understand:
This doc is short and not all that helpful.
What might you people add to my discussion of lambdas?
How would you explain or breakdown the syntax of the lambda expression above or other lambda expressions elsewhere?
names = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos', 'julian sequeira', 'sandra bullock', 'keanu reeves', 'julbob pybites', 'bob belderbos', 'julian sequeira', 'al pacino', 'brad pitt', 'matt damon', 'brad pitt']I am trying to return the names list (above) and sorted desc by surname. Leveraging this answer on Stack Overflow, here is my working solution:
def sort_by_surname_desc(names): return sorted(names, key=lambda x: x.split()[1], reverse=True)What I understand:
- The sorted built-in takes three parameters.
- The first parameter is a mutable iterable (in my case list of names).
- The second parameter is a
key
which needs to be callable like another function or in my case a lambda. According to the official Python docs, the key is called exactly once for each iterable. The official Python docs, when describing how to use sorted(), for the key parameter they also use a lambda.
- In my code sample,the
.split
cuts up each list item string into two and pulls each second result as specified by[1]
.
- The final parameter specifies that the list be sorted alphabetically in reverse.
What I don’t understand:
- The lambda
def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11))The output is 22. The lambda expression throws me off. I re-wrote
myfunc()
which produces the same output but uses a regular function:def my_second_func(n, a): return n * a print(my_second_func(11,2))I still don't understand. The Python docs describe lambda expressions in this way:
Quote:lambda_expr ::= "lambda" [parameter_list] ":" expression lambda_expr_nocond ::= "lambda" [parameter_list] ":" expression_nocondLambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expressionlambda parameters: expression
yields a function object. The unnamed object behaves like a function object defined with:
def <lambda>(parameters): return expressionSee section Function definitions for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations.
This doc is short and not all that helpful.
What might you people add to my discussion of lambdas?
