Simple question, I’ve scaled down a problem I’m having where a list which I’ve retrieve from an object is changing when I append more data to the object. Not to the list.
Can anyone help my understand the behavior of python?
class a():
def __init__(self):
self.log = []
def clearLog(self):
del self.log[:]
def appendLog(self, info):
self.log.append(str(info))
def getLog(self):
return self.log
if __name__ == '__main__':
obj = a()
obj.appendLog("Hello")
# get an instance as of this moment....
list = obj.getLog()
print list
obj.appendLog("World")
# print list, BUT we want the instance that was obtained
# before the new appendage.
print list
OutPut:
['Hello']
['Hello', 'World']
The only place you create a new list is in the constructor, with the statement:
Later, when you do:
just puts a reference to the same list in a new variable (note, don’t use
listas a variable name, since it shadows the type). It does not create or clone a list in any way. If you want to clone it, do:
You can also use a tuple (read-only sequence), if that’s appropriate:
This may help minimize confusion about which should be modified.