Why doesn't this work?
lambda: print "x"
Is this not a single statement, or is it something else?
The documentation seems a little sparse on what is allowed in a lambda...
A lambda's body has to be a single expression. In Python 2.x, print is a statement. However, in Python 3, print is a function (and a function application is an expression, so it will work in a lambda). You can (and should, for forward compatibility :) use the back-ported print function if you are using the latest Python 2.x:
In [1324]: from __future__ import print_function
In [1325]: f = lambda x: print(x)
In [1326]: f("HI")
HI
In cases where I am using this for simple stubbing out I use this:
fn = lambda x: sys.stdout.write(str(x) + "\n")
which works perfectly.
what you've written is equivalent to
def anon():
return print "x"
which also results in a SyntaxError, python doesn't let you assign a value to print in 2.xx; in python3 you could say
lambda: print('hi')
and it would work because they've changed print to be a function instead of a statement.
The body of a lambda has to be an expression that returns a value. print, being a statement, doesn't return anything, not even None. Similarly, you can't assign the result of print to a variable:
>>> x = print "hello"
File "<stdin>", line 1
x = print "hello"
^
SyntaxError: invalid syntax
You also can't put a variable assignment in a lambda, since assignments are statements:
>>> lambda y: (x = y)
File "<stdin>", line 1
lambda y: (x = y)
^
SyntaxError: invalid syntax
You can do something like this.
Create a function to transform print statement into a function:
def printf(text):
print text
And print it:
lambda: printf("Testing")
With Python 3.x, print CAN work in a lambda, without changing the semantics of the lambda.
Used in a special way this is very handy for debugging.
I post this 'late answer', because it's a practical trick that I often use.
Suppose your 'uninstrumented' lambda is:
lambda: 4
Then your 'instrumented' lambda is:
lambda: (print (3), 4) [1]
The body of a lambda has to be a single expression. print is a statement, so it's out, unfortunately.
Here, you see an answer for your question. print is not expression in Python, it says.
in python3 print is a function, and you can print and return something as Jacques de Hooge suggests, but i like other approach: lambda x: print("Message") or x
print function returns nothing, so None or x code returns x
other way around: lambda x: x or print("Message") would print message only if x is false-ish
this is widely used in lua, and in python you can too instead of a if cond else b write cond and a or b
If you want to print something inside a lambda func In Python 3.x you can do it as following:
my_func = lambda : print(my_message) or (any valid expression)
For example:
test = lambda x : print(x) or x**x
This works because print in Python 3.x is a function.
Related
I am trying to do something like this:
def myFunc(y):
aVariable = "a"
bVariable = "b"
y(aVariable,bVariable)
def main():
myFunc(lambda a,b: a+=b)
and expecting the output to be "ab".
Instead I get the following error:
File "<stdin>", line 7
myFunc(lambda x, y: x += y)
^
SyntaxError: invalid syntax
Only expressions are allowed in the body of a lambda function; a += b is an augmented assignment statement, when compiled, this will lead to a SyntaxError as the grammar doesn't allow it.
You can either change it to simply return the addition:
lambda a,b: a+b
and then proceed to set the result of calling it to a appropriately:
a = y(aVariable,bVariable)
You could of course resort to using the function that is used for that operation. Though you could directly do lambda a, b: a.__iadd__(b), this is clunky and using dunders like this isn't the best practice. Instead, you should use the appropriate operation from the operator module.
The iadd function from operator allows you to bypass this "restriction" if you truly need to. Function calls are expressions, as such, it is allowed to use them in the body of the lambda function. A simple import is needed:
from operator import iadd
and then, redefine the lambda passed to myFunc to use iadd:
myFunc(lambda a,b: iadd(a, b))
Adding these all together while also adding appropriate returns in myFunc and main:
from operator import iadd
def myFunc(y):
aVariable = "a"
bVariable = "b"
return y(aVariable,bVariable)
def main():
return myFunc(lambda a,b: iadd(a, b))
results in ab when main is called.
I am trying to print a string in all uppercase letters. When I run the print command it prints the type of x and the location.
Why does it print the operation instead of the result?
x = 'bacon'
x = x.upper
print x
>>>
<built-in method upper of str object at 0x02A95F60>
upper (and all other methods) is something like "function ready to use", that way you can do:
x = 'bacon'
x = x.upper
print x()
But the most common to see, and the way I think you want is:
x = 'bacon'
x = x.upper()
print x
"Ridiculous" example using lambda:
upper_case = lambda x: x.upper()
print(upper_case) # <function <lambda> at 0x7f2558a21938>
print(upper_case('bacon')) # BACON
Everything in Python is an object, including functions and methods. x.upper is the upper attribute of x, which happens to be a function object. x.upper() is the result of trying to call that attribute as a function, so you are trying to do
print x.upper()
As an aside, you can try to call any object in Python, not just functions. It will not always work, but the syntax is legitimate. You can do
x = 5
x()
or even
5()
but of course you will get an error (the exact same one in both cases). However, you can actually call objects as functions as long as they define a __call__ method (as normal functions do). Your example can actually be rewritten as
print x.upper.__call__()
Is there any way how to code recursive function containing if with lamba?
Is possible to rewrite this using lambda.
def factorial(x):
if x <= 1:
return 1
return x * factorial(x - 1)
print(factorial(5))
No, or at least not without assigning the function to a variable and then using that name to call it. But you still cannot use any statements in the function.
In any case, don't do that. A lambda function is exactly like a normal def function in Python besides the restriction that it cannot contain statements.
The only reason to use a lambda in Python is to avoid defining an named function if you just need a simple callable returning some value.
Yes, it is possible for this specific case.
>>> factorial = lambda x: 1 if x < 1 else x * factorial(x - 1)
>>> factorial(5)
120
I wouldn't recommend it though. A standard function definition seems far more readable to me.
>>> l = lambda i: 1 if i<=1 else i * l(i-1)
>>> l(5)
120
>>> 5*4*3*2*1
120
I am using the Canopy IDE. I am a beginner in Python. I was taking the edX online course where I stumbled upon this code:
def a(x,y,z):
if x:
return y
else:
return z
def b(p,r):
return a(p>r,p,r)
print a(3>2,a,b)
I cannot understand how the statement a(3>2,a,b) works. In essence, how function comparison works in python. When I executed the code in my IDE, it gave the following output.
<function a at 0x00000000088F4198>
Your call:
a(3>2, a, b)
Resulted in parameter 'a' being returned. Parameter a is the function used to perform comparison:
def a(x,y,z):
if x:
return y
else:
return z
Default string representation of a function is:
<function (name) at 0x(address in memory)>
Try running function a() with different arguments, like
a(3>2, "Greater", "Smaller")
Or use Python ternary operator:
result = "Greater" if 3 > 2 else "Smaller"
Toying around with lambdas in Python I discovered that the following code is legal in Python 2.7.3 and returns the lambda:
x = lambda: 1 if x else 2
Why does the lambda define x when used in this way?
Edit: Python syntax is apparently too hard for me, see the accepted answer…
Why does the lambda define x when used in this way?
It doesn't. The assignment x = [any expression] defines x to be [any expression]. In this case, the expression is lambda: 1 if x else 2, which evaluates to a function object without arguments, and it is that which x holds.