[python] Add an object to a python list

I am trying to add an object to a list but since I'm adding the actual object when I try to reset the list thereafter, all the values in the list are reset. Is there an actual way how I can add a monitor object to the list and change the values and not affect the ones I've already saved in the list?

Thanks

Code:

arrayList = []

for x in allValues:


        result = model(x)

        arrayList.append(wM)

        wM.reset()

where wM is a monitor class - which is being calculated / worked out in the model method

This question is related to python object

The answer is


You need to create a copy of the list before you modify its contents. A quick shortcut to duplicate a list is this:

mylist[:]

Example:

>>> first = [1,2,3]
>>> second = first[:]
>>> second.append(4)
>>> first
[1, 2, 3]
>>> second
[1, 2, 3, 4]

And to show the default behavior that would modify the orignal list (since a name in Python is just a reference to the underlying object):

>>> first = [1,2,3]
>>> second = first
>>> second.append(4)
>>> first
[1, 2, 3, 4]
>>> second
[1, 2, 3, 4]

Note that this only works for lists. If you need to duplicate the contents of a dictionary, you must use copy.deepcopy() as suggested by others.


while you should show how your code looks like that gives the problem, i think this scenario is very common. See copy/deepcopy


If i am correct in believing that you are adding a variable to the array but when you change that variable outside of the array, it also changes inside the array but you don't want it to then it is a really simple solution.

When you are saving the variable to the array you should turn it into a string by simply putting str(variablename). For example:

array.append(str(variablename))

Using this method your code should look like this:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(str(wM))        #this is the only line that is changed.
    wM.reset()