Ask coding questions

← Back to all posts
1
How to get the result, not a link to memory (python)
ChapeauClaque (0)
squares = []
for x in range(5):
    squares.append(lambda x : x**2)
print (list(squares))

Result: [<function <lambda> at 0x7f87461dee18>, <function <lambda> at 0x7f87419b40d0>, <function <lambda> at 0x7f87419b4158>, <function <lambda> at 0x7f87419b41e0>, <function <lambda> at 0x7f87419b4268>]
Tell me, please, how to get a list of function results

Commentshotnewtop
1
leon332157 (55)

You don't have to use lambda functions, u can do x**2 directly.

1
ChapeauClaque (0)

@leon332157 The problem is not that I can not use the function. Why the function works this way.

1
leon332157 (55)

@ChapeauClaque You are appending the lambda object instead of the result because in Python everything is an object. So if you want to get the result, u have to call the function, can be done with squares.append((lambda x : x**2)(x)).

1
ChapeauClaque (0)

@leon332157 Where in the documentation does it say that? If you don't mind, give me a link.

1
ChapeauClaque (0)

@leon332157 It is not interesting to know the result, I need to understand how it works.