I can't understand how lambdas in comprehension lists works.
Please help me undestand this mechanism, and sorry but I'm learning right now and the explications that I can find online are not really clear to me.
def times_two(a): return a * 2
def times_three(a): return a * 3
numbers = [1, 2, 3, 4]
both_functions = [times_two, times_three]
for number in numbers:
print(list(map((lambda x: x(number)), both_functions)))
What does (lambda x: x(number)) do exacly, why is there a second x, what kind of parameter is?
Other example:
is_even_list = [lambda a=x: a * 10 for x in range(0, 6)]
for item in is_even_list:
print(item())
Why here there is an a=x, usually lambdas doesn't have only one parameter?
The last one:
A = [1, 2, 3, 4]
B = [lambda: _ for _ in A]
C = [_() for _ in B]
print(A)
print(B)
print(C)
Here what does _() do?
CodePudding user response:
The lists you're iterating over contain functions. Inside the iteration, you call the function in the current iteration item.
lambda x: x(number)
means that it receives a function in x
, and then calls that function with number
as the argument.
for item in is_even_list:
print(item())
loops over the functions in is_even_list
, and calls each of those functions.
[_() for _ in B]
_
is just a variable name, although conventionally it's only used for iterations where you don't use the iteration item. B
contains a list of functions, so this calls each of those functions and returns a list of the results.
CodePudding user response:
list(map((lambda x: x(number)), both_functions))
map loops over the items defined in both_functions which means for each number it loops over times_two and times_three function. ie: when number is 1, it produces output [times_two(1), times_three(1)] equals [2, 3]
CodePudding user response:
What does
(lambda x: x(number))
do exactly
In terms of the comprehension, nothing specific. It is an argument of map()
why is there a second x, what kind of parameter is?
It is a callable function object.
Why here there is an a=x
It seems to be defining a partial function with a parameter for the range()
. That syntax is new to me...
If you remove =x
, then you get an error missing 1 required positional argument: 'a'
, which is the same error if you had defined a regular function def foo(a):
and just called foo()
in the loop.
usually lambdas doesn't have only one parameter
They are in-line functions, so no, they can have as many as necessary.
what does _() do
_
is just a variable. It can be assigned to a callable. _()
calls a function named _
.