0

im working on a python script that takes an array and rotates it, but i've been having the same problem. This is the code:

def parse(string):
    string += " "
    a = 0
    arr = []
    arrI = 0
    for i in range(1, len(string)):
        if string[i] == " ":
            arr.append("")
            for j in range(a, i):
                arr[len(arr) - 1] += string[j]
            a = i
    return(arr)
a = parse(input())
N = int(a[0])
K = int(a[1])
array = parse(input())

temp = array
array[0] = temp[N - 1]
for i in range(1, N - 1):
    array[i] = temp[i - 1]
print(array)

Keep in mind that N is the amount of integers in the array and I haven't used K yet, so ignore it. For the inputs I do N = 5 and array = 1, 2, 3, 4, 5. I expect to get 5 1 2 3 4 but instead get 5 5 5 5 5. I eventually found out that temp was changing even when I never told it to. When I add prints,

print(temp)
array[0] = temp[N - 1]
print(temp)

I am surprised to find that the two prints had different answers, even when I never told temp to change, just array.

I made a temp because if I changed one part of array, I can't use it later. Then, I tried a second layer, where

temp1 = answer
temp = temp1

and in the for loop at the endtemp = temp1Same answer. Next, I thought maybe I could make a separate variable containing the number I want, so it can not be traced back to temp.So, instead of array[i] = temp[i - 1] , I did

item = temp[i - 1]
array[i] = item

Nothing changes. Also, I'm not asking for how to rotate an array, im asking how to fix this problem. Thank you.

Anders C
  • 3
  • 3
  • 1
    Python variables store references to objects. `temp = array` copies the reference to the same object from "array" to "temp". For lists you can create a shallow copy with `temp = array[:]`. – Michael Butscher Dec 12 '22 at 05:31
  • `answer`, `temp`, and `temp1` are not three different lists. They are three references to the SAME list. Change one, and it is visible under all three names. Use `temp1 = answer[:]` if you want a copy. – Tim Roberts Dec 12 '22 at 05:31

1 Answers1

0

Lists in python are mutuables, so when you change any of them, the other one will be changed as well.

To avoid this behavior, do something like:

a = b.copy()
# or
a = b[:]
# or 
a = list(b)

You can read more about that in Lists: Mutable & Dynamic

Assem
  • 11,574
  • 5
  • 59
  • 97