1

Here is my code:

class Foo(object):
    def __init__(self, x, y):
        self.x     = x
        self.y     = y

    def func(self):
        self.x[0] -= 1
        self.y    -= 1


x = [10]
y = 10



a = Foo(x, y)
a.func()

print(x, y)

Output is ([9], 10). Why does passing a list to an instance variable and then changing the instance variable also change the original list, but not the original integer?

How do you pass a list to an instance variable in Python, and then change the instance variable without affecting the original list?

2 Answers2

1

I believe this is because lists are mutable, while integers are immutable. Once you make a change to a list, the same list is returned. Once you change an integer, a "copy" of the integer is returned. So func is changing the x, but creating a new y

AC1009
  • 64
  • 3
0

The list is a mutable object; the assignment copies the reference, so that when you change the value of one element, you change the original object.

An integer is not mutable; when you change the value, Python changes the reference to a new object with the new value. self.y does not refer to the same object as y any more.

Prune
  • 76,765
  • 14
  • 60
  • 81