>>> def itself_and_plusone(x):
... return x, x+1
...
>>> itself_and_plusone(1)
(1, 2)
>>> (lambda x: x,x+1)(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
why? and workaround with lambda? not by
>>> (lambda x: (x,x+1))(10)
(10, 11)
because it returns a tuple(or list..) and unpacking the tuple would be required
Without the parentheses it is interpreted as follows:
This fails because the second
xis outside the lambda expression. And even ifxwere defined, it would still fail because you can’t use a tuple as if it were a function.This simple variation shows what is going on:
Notice that the 43 is because the
xin the outer scope is used, not thexin the lambda function.The correct way to write it is
lambda x: (x,x+1). This does indeed, as you point out, return a tuple, but so does your original function: