-1

I'm supposed to rotate the list iteratively which means put the first element to the last, and the rest move forward until it back to the original list.

Here is the main function

a = input("Enter your list: ")
alist = a.split(' ')
alist = [int(alist[i]) for i in range(len(alist))]
origin = alist
rotate(alist, origin)

And this is the rotate funcation body

def rotate(lst1, x):
        n = lst1.pop(0)
        lst1.append(n)
        print(lst1)
        print(x)
        if lst1 != x:
            rotate(lst1, x)

The problem is why the 'origin' is changing as the 'lst1' changes, and how what should I do to prevent it.

Chris Su
  • 3
  • 1
  • Do `origin = alist[:]` or `origin = alist.copy()` instead of `origin = alist`. Read this [copy in python](https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/#:~:text=A%20shallow%20copy%20constructs%20a,objects%20found%20in%20the%20original.) – Avinash May 13 '22 at 14:34
  • Hi Chris, when you perform the following operation: origin = alist both variables are pointing to the same memory address where the list is stored, that is the reason why the changes in one list are reflected in the other, because both are the same list (based in the memory address) – Juan Castelli May 13 '22 at 14:36
  • 1
    Obligatory reading: https://nedbatchelder.com/text/names.html – chepner May 13 '22 at 14:37

1 Answers1

0

the problem is that when you're doing origin = alist you're actually creating a pointer to the same object, you're not creating a copy of the list. In order to create a copy of the list I suggest you use the following notation:

origin = alist[:]

By doing that you're creating another object with the same elements inside so that's a copy!