Mannu_050
Mannu_050

Reputation: 23

What is the use of () in the Python code?

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?

Upvotes: 0

Views: 98

Answers (3)

Blusky
Blusky

Reputation: 3794

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

Upvotes: 4

Nj Nafir
Nj Nafir

Reputation: 568

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

class Name:
    ...

Name()

or,

name = Name()

Upvotes: 0

Gamopo
Gamopo

Reputation: 1598

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 ()

Upvotes: 0

Related Questions