Lambda function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Lambda function (/thread-19817.html) |
Lambda function - Uchikago - Jul-16-2019 Hi, i'm a bit confused with this code x=10 x=lambda : x+2 print(x())because the right side of the '=' is evaluated first so this should have returned 12 rather than reported an error as it did error: x=lambda : x+2 TypeError: unsupported operand type(s) for +: 'function' and 'int'Please explain why this code doesn't work RE: Lambda function - Gribouillis - Jul-16-2019 After the two first lines, x is no longer an integer, it is an anonymous function >>> x = 10 >>> x = lambda: x + 2 >>> x <function <lambda> at 0x7fb32e167048>At this stage, x + 2 has not yet been executed. It's only executed when you call x() but then it is an error because you're trying to add a function and an integer>>> x() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> TypeError: unsupported operand type(s) for +: 'function' and 'int'See this other example which is a regular function but works the same >>> y = 122 >>> def spam(): ... print('The value of y is', y) ... >>> y = 314 >>> spam() The value of y is 314 RE: Lambda function - millpond - Jul-16-2019 It appears that the problem is that line 2 assigns the return of a function to its own variable. x=10 y = (lambda x : x+2 ) print(y(x))Works, RE: Lambda function - perfringo - Jul-16-2019 Just a gentle reminder - quote from PEP 8 -- Style Guide for Python Code >>> Programming Recommendations Quote:Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier. |