In the following code, why does the vector instance a
change after a.add(b)
?
class Vector:
def __init__(self, arg):
# assign to a var
self._vector = arg
def add(self, arg):
result_vector = self._vector
# add elements
for i in range(len(arg._vector)):
result_vector[i] += arg._vector[i]
return result_vector
def print(self):
print(self._vector)
a = Vector([1, 2, 3])
b = Vector([3, 4, 5])
a.print()
b.print()
print(a.add(b))
a.print()
b.print()
I was expecting result_vector
to contain the addition but that a
would retain its own value.
E.g. running this code outputs
[1, 2, 3]
[3, 4, 5]
[4, 6, 8]
[4, 6, 8] # <--- why has a changed?
[3, 4, 5]