Python lambda syntax | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Python lambda syntax

It appears there are two ways of writing a function in lambda syntax (examples form Python course): ``` #separating the expression and arguments with brackets: print((lambda x: x**2 + 5*x + 4) (-4)) ``` Output: >>> 0 ``` #separating the expression and arguments with a comma: print(lambda x: x**2 + 5*x + 4, -4) ``` Output: >>> <function <lambda> at 0x013F39C0> -4 1. What reasons for choosing one notation over the other 2. I'm assuming that anonymous functions are meant for one-time use. If the argument is already given with a specific value and the function isn't gonna be reused, what need is there for the x variable? I doesn't work to write the function *directly providing the value of x* instead of the variable name, like so: ``` print(lambda -4: x**2 + 5*x + 4) ``` ... but why not?

27th Jun 2019, 10:38 AM
Ben Opp
4 Answers
+ 7
lambda x: is roughly equal to def some_func(x): x is just the name for the argument you are going to pass later. If you want to call a function, you have to add the parentheses with the arguments, like with normal functions. print(some_func) Will just give you the function identification line, but nothing else, since you don't actually call it. print(some_func, 5) Doesn't call some_func - you are passing two arguments to the print function, one being a function name and one an int, so they will just be printed out. lambda calls often need parentheses around the function because they come late within operator precedence and can't be properly parsed otherwise.
27th Jun 2019, 10:53 AM
HonFu
HonFu - avatar
+ 7
print(lambda x: x**2 + 5*x + 4, -4) is not a special lambda syntax. You're simply calling the print() method with two arguments; 1) lambda x: x**2 + 5*x + 4, and 2) -4. print(lambda -4: x**2 + 5*x + 4) doesn't work because Python has no idea what x is. If you used the same syntax for a lambda function with more than one variable: lambda -5, 28: x ** y, how do you expect Python to know what value (-5, 28) corresponds with what variable name (x, y)?
27th Jun 2019, 10:55 AM
Anna
Anna - avatar
+ 3
There are some functions that especially need a function as their arguments. Like you might already seen the 2 functions "map" and "filter", they are functions, that require a function as the first argument, and will run the given function for all the arguments of the given iterable(s). Lambdas are often very useful for functions, that require another functions as arguments.
27th Jun 2019, 11:22 AM
Seb TheS
Seb TheS - avatar
+ 2
You can use something called named lambdas: x = lambda a: a*a print(x(10)) Output 100 And use lambdas as return values for a function: def func(x): return lambda x*x print(func(10))
27th Jun 2019, 11:11 AM
alvaro.pkg.tar.zst
alvaro.pkg.tar.zst - avatar