Home > OS >  I want to make a function that circulates the elements in a list, but it changes the list globally
I want to make a function that circulates the elements in a list, but it changes the list globally

Time:11-10

The function cycle removes the first element of a list puts it in the last position. I used pop and append to do so. The problem is that if you use:

l=[1,2,3]
assert(cycle(l)== [2,3,1])
assert(cycle(cycle(l))== [3,1,2])

it gives you an assertionerror, so i thought maybe the list is changed globally, but i do not want that and i cannot find a solution. I am new to programming.

l=[1,2,3]
def cycle(y):
    x=y.pop(0)
    y.append(x)
    return (y)
assert(cycle(l) == [2, 3, 1])
assert(cycle(cycle(l)) == [3, 1, 2])
assert(l == [1, 2, 3])

I tried changing my code a little by using a copy of y to reset the list in the function afterwards but it seems that did not work either. Maybe i just did it wrong.

l=[1,2,3]
def cycle(y):
    z=y.copy
    x=y.pop(0)
    y.append(x)
    return (y)
    y=z
assert(cycle(l) == [2, 3, 1])
assert(cycle(cycle(l)) == [3, 1, 2])
assert(l == [1, 2, 3])

CodePudding user response:

Well, this is because Python does pass pointer to the list, it does not creates its own copy. So, you can simply use this:

from copy import deepcopy

cycle(deepcopy(l))

So your list won't change globally.

CodePudding user response:

    print(cycle(l))
    print(cycle(cycle(l)))
    print(l)

    assert(cycle(l) == [2, 3, 1])
    assert(cycle(cycle(l)) == [1, 2, 3])
    assert l == [1, 2, 3]

I think you need to update the 2nd assert expected output. cycle(l) call return [3,2,1] when you pass this to cycle(cycle(1)) again it will return [1,2,3].

CodePudding user response:

Use deepcopy instead of copy and play with the copied object

from copy import deepcopy
l=[1,2,3]
def cycle(y):
    z=deepcopy(y)
    x=z.pop(0)
    z.append(x)
    return (z)
assert(cycle(l) == [2, 3, 1])
assert(cycle(cycle(l)) == [3, 1, 2])
assert(l == [1, 2, 3])
  • Related