0
for x in range(10):
   arr.append(lambda:x**2)
arr[4]()

Expected output: 16 or nothing because no print statement But output, when I run, is 81. Why so?

Mannu_050
  • 23
  • 1
  • You're running this in an interactive interpreter. (That, and https://stackoverflow.com/questions/12423614/local-variables-in-nested-functions) – user2357112 Jul 13 '20 at 09:54
  • 1
    each element in an array is a function (or lambda). So arr[4] is a function and () is a function call – Benjamin Jul 13 '20 at 09:54
  • Also, it sounds like you already know what all the parentheses do in this code, if you understood enough to expect 16 or nothing. – user2357112 Jul 13 '20 at 09:55

3 Answers3

4

In your code, arr.append(lambda:x**2), x is scoped outside the function.

When you finish the loop, x is set to 9 (0 to 9).

Then, x**2 is 81, so arr[4]() will re-evaluate x, so the result is 81.

Just for fun, you can attempt what you want with the following:

f_generator = lambda i: lambda: i**2
arr = [f_generator(i) for i in range(10)]
arr[4]()  # 16
Blusky
  • 3,470
  • 1
  • 19
  • 35
0

To get the effect you want, you should remove the lambda like this:

arr = []
for x in range(10):
   arr.append(x**2)
print(arr[4])

because otherwise you are storing a function, not a number. Notice that now you don't need ()

Gamopo
  • 1,600
  • 1
  • 14
  • 22
0

() is used for calling any object, it can be a method or class like,

class Name:
    ...

Name()

or,

name = Name()
Nj Nafir
  • 570
  • 3
  • 13