0

As per my knowledge the Python interpreter creates references from 0 to 256 for int objects, at the start itself. Here I got output 3,[44,2,3], for the list I understood, but why did the same thing not happen with the int object? I expected the output to be 1,[44,2,3]. Can anyone please explain this behavior to me? I use Python 3.

def change(var, lst):
    var = 1
    lst[0] = 44
k = 3
a = [1, 2, 3]
change(k, a)
print(k)
print(a)

Output:

3
[44,2,3]

Expected output:

1
[44,2,3]
Ruan
  • 219
  • 5
  • 9
  • 2
    You reassign `var` to a different value. I'm not sure what you think that has to do with the implementation detail that Python caches references for certain ints. – Daniel Roseman Nov 18 '19 at 13:34
  • 2
    You're doing two fundamentally different operations. If you did `lst = [44, 2, 3]`, i.e. assigning a new list to the local name in the same way you're assigning a new int `1` to the local name `var`, you'd see the same behaviour. – jonrsharpe Nov 18 '19 at 13:35

0 Answers0