0

I'd run on a subtle bug on an involved python script. Basically what went wrong looks like this

def inc(x):
    return x+1

a = 1
b = 2
c = 3

for x in [a,b]:
    print(id(x), id(a), id(b))

for x in [a,b]:
    x = inc(x)
c = inc(c)

print(a,b,c)

As the first for loops shows the iterator x is taking a reference to the ongoing variable. Still when we assign a value to that iterator, the pointee(referencee) variable is not changing. I really didn't expect that behavior, this is not python, isn't? Can some one throw some light on this?

Juan Chô
  • 542
  • 6
  • 23
  • `a` and `b` are not mutable so you can't change. Even if you change nothing will happen – deadshot Oct 15 '20 at 10:26
  • It's not clear sure what you consider a bug. Maybe look at https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference – buran Oct 15 '20 at 10:26

1 Answers1

0

For your first loop you print id's of x, a, b. x - is a local variable, not an a or b. Though it holds reference to the same number, it is not the same instance of reference as a or b. Integers are immutable in python. When you perform something like x = x + 1 what you do is not changing value by the reference, but changing reference to point to new value.

Also, keep in mind that in python integers from -5 to 255 are computed even before they are referenced. That's one of pythons many optimizations.

So on first iteration x holds a value of a and as it is 1 - it is already computed and they point to the same place in memory. On the second iteration x points to the same value as b. But in neither case the reference itself is the same.

If your a, b, c were mutable like lists or dicts you would observe a different behaviour. Probably, the one you expect.

go2nirvana
  • 1,598
  • 11
  • 20
  • This is not true, it happens with mutable stuff also, just try it! Take a list and you will see. This has nothing to do with integer: it happens with other variables. My original problem was with numpy arrays which are mutable. – Juan Chô Oct 15 '20 at 12:01
  • If you reassign mutable variable - that won't happen, but if you would, say, append to a list - it would. – go2nirvana Oct 15 '20 at 15:11