Search code examples
pythonarrayspython-3.xlistenumerate

Why we have messed up values when we use enumerate to copy values from one array to another?


This is my code with comments saying the output of the print functions:

def rotLeft(a, d):
    rotArray = a
    arraySize = len(a)

    print(a)#[1, 2, 3, 4, 5]

    for index, item in enumerate(a):
        print(index) # 0 1 2 3 4
        print(item) # 1 1 1 1 1
        rotArray[(index + 1) % arraySize] = item

    return rotArray

if I remove the last for instruction, we can retrieve the correct values. But if we maintan, somehow it does mess up with my original a array. Why this happen, and what is the good practice in this case?


Solution

  • rotArray is referring to a, thus modifying it modifies a.

    You can do this:

    rotArray = a.copy()