0

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
ml-moron
  • 888
  • 1
  • 11
  • 22
LBaelish
  • 649
  • 1
  • 8
  • 21
  • 1
    You want to copy your array, for options see http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python – Matthew Mar 16 '16 at 18:59
  • Yeah that works, I copied redundancies array instead of just setting it equal. What am I really doing then in this existing code? Making y a pointer? – LBaelish Mar 16 '16 at 19:02

1 Answers1

1

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.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119