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
You can insert an item at any index (position) with the insert() method. Set the index for the first parameter and the item to be inserted for the second parameter. The index at the beginning is 0 (zero-based indexing). For negative values, -1 means one before the end.
If you are using array module, you can use the concatenation using the + operator, append(), insert(), and extend() functions to add elements to the array. If you are using NumPy arrays, use the append() and insert() function.
One of the best practices to do what you want to do is by using + operator. The + operator creates a new list and leaves the original list unchanged.
Is your problem similar to this:
l = [[0]] * 4 l[0][0] += 1 print l # prints "[[1], [1], [1], [1]]"
If so, you simply need to copy the objects when you store them:
import copy l = [copy.copy(x) for x in [[0]] * 4] l[0][0] += 1 print l # prints "[[1], [0], [0], [0]]"
The objects in question should implement a __copy__
method to copy objects. See the documentation for copy
. You may also be interested in copy.deepcopy
, which is there as well.
EDIT: Here's the problem:
arrayList = [] for x in allValues: result = model(x) arrayList.append(wM) # appends the wM object to the list wM.reset() # clears the wM object
You need to append a copy:
import copy arrayList = [] for x in allValues: result = model(x) arrayList.append(copy.copy(wM)) # appends a copy to the list wM.reset() # clears the wM object
But I'm still confused as to where wM
is coming from. Won't you just be copying the same wM
object over and over, except clearing it after the first time so all the rest will be empty? Or does model()
modify the wM
(which sounds like a terrible design flaw to me)? And why are you throwing away result
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With