'List changed in a function [duplicate]

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.



Solution 1:[1]

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!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 federicknellus