0
What does lambda x=x mean? I saw some answers in internet but not understanding. Could anyone explain in very easy terms pls
a=[lambda x=x:x*10 for x in range(10)] for i in a: print(i())
9 Answers
+ 1
to make a list of numbers using lambda function, write this:
a = [(lambda x: x*10)(x) for x in range(10)]
note: the lambda takes an argument in parenthesis - (x) - and the lambda itself is also surrounded with (). so the x*10 runs for every number in range 10, and an integer value is being returned, not a callable. try it!
+ 3
You can learn about the lamba function here. It has a history of how it came to be. As well as explaining each part in detail
Scroll down to the first example to see it all broken down step by step.
https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-lambda/
+ 2
You can give function parameters default values using the = operator.
Example of a function having parameter spam given default value of 8:
def f(spam = 8):
return spam * 7
If you call the function as f() the parameter spam won't get given a value, so it will use the default value 8 instead, the return value will be 56.
The given definition:
a=[lambda x=x:x*10 for x in range(10)]
is not very readable code, to increase readability it could be written as:
a=[lambda x=y:x*10 for y in range(10)]
and there you would more easily see, that the definition creates 10 functions with parameters taking different default values from y in range(10).
+ 2
Levi There is no errors in [lambda x: x%10 for x in range(10)], it's just about how the functions were called.
if you call them like in the given for loop:
for i in a:
print(i())
you are calling the 10 functions without arguments while the functions are expecting 1 argument and that's where the error comes from.
+ 1
Seb TheS Ohok. Getting some understanding nw !! Thanks š
0
Seb TheS OK but default value is optional rgt ! So why I am I seeing an error when I remove that x ?
Like, lamba x:x%10 for x in range(10) ?
0
Levi The optionality of the default value depends on how you are calling the function.
having the default values for the function parameter allows your function to be called without arguments (because the default value will replace the missing argument) and both these would work:
i()
i(arg)
if you remove the default value you are forced to call the function with an argument and only this works:
i(arg)
and this would cause an error:
i()
0
Seb TheS
** Sry for asking repeatedly because I am not able to get clear understanding **
But for this scenario why do we even need a default value. It already has the input from 0-10.
lambda x:x%10 for x in range(10) would simply work rgt ? Why it isn't working ?
0
Levi by creating a list using
[lambda x: x%10 for x in range(10)]
you are creating a list of functions, because lambda returns a callable (function)