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
2
  • 1
    You want to copy your array, for options see stackoverflow.com/questions/2612802/… Commented Mar 16, 2016 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? Commented Mar 16, 2016 at 19:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.