-1

I have a function that I define in a while loop that is called by code I do not control.

In the following example, access() always returns the value 1. Why? And how can I make access() return the latest value?

while True:
    g = [1,2,3]

    def access():
        return g[0]

    print(access())
    g[0] += 1

The same seems to be true for lambdas. I cannot make g global.

2080
  • 1,223
  • 1
  • 14
  • 37

1 Answers1

4

Because the g variable is always reinitialized to [1,2,3].

Just move it outside the while loop.

g = [1,2,3]
while True:
    .....
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128