Reputation: 699
Never run run accross this in python before, and I'm wondering why it happens and how I can avoid it. When I set y = redundanciesArray
I want to make a copy of the array, change a value at some index, act on that change, and then reset y
to be a fresh copy of the array. What happens is that on the first pass redundanciesArray = [2,1,1,1,1]
and on the second pass it is [2,2,1,1,1]
. It's sort of like y
acting as a pointer to the redundanciesArray
. I guess I'm not using arrays correctly or something, hopefully someone can shine a light on what I'm missing here.
redundanciesArray = [1, 1, 1, 1, 1]
probabilityArray = [0.5, 0.5, 0.5, 0.5, 0.5]
optimalProbability = 0
index = -1
for i in range(0, len(redundanciesArray)):
y = redundanciesArray
y[i] = y[i] + 1
probability = calculateProbability(y, probabilityArray)
//calcuateProbability returns a positive float between 0 and 1
if(probability > optimalProbability):
optimalProbability = probability
index = i
Upvotes: 0
Views: 43
Reputation: 52169
Python uses names, which behave somewhat similar to references or pointers. So doing
y = redundanciesArray
will just make y
point to the same object that redundanciesArray
already pointed to. Both y
and redundanciesArray
are just names ("references to") the same object.
If you then do y[i] = y[i] + 1
, it will modify position i
in the object pointed to by both y
and redundanciesArray
.
Upvotes: 1