I have tried:
>>> l = [1,2,3]
>>> x = 1
>>> x in l and lambda: print("Foo")
x in l && print "Horray"
^
SyntaxError: invalid syntax
A bit of googling revealed that print is a statement in python2 whereas it’s a function in python3. But, I have tried the above snipped in python3 and it throws SyntaxError exception.
Any idea on how can I do it in one line? (Readability or google programming practice is not an issue here)
lambdacreates, well a lambda. It needs to be called to execute it. You cannot do this that way, because Python doesn’t allow statements in this context, only expressions (including function calls).To make
printa function in Python 2.x, try:Be wary though. If you try:
it won’t work, because print returns
None, so the firstandexpression is False, so bothprints will be executed. In Python 3.x you don’t need the import.If you won’t have complex short-circuiting (i.e. just one
andoror), or you know your functions or expressions won’t surprise the short-circuiting logic, there’s nothing wrong with the code. Otherwise, try the non-short-circuiting 1-liner:This form is recommended only if the probability/expectation of the conditional to be True is vastly higher than being False. Otherwise, plain good-old
if-elseis the way to go.