1

Newly starting to learn python I am trying to write a function to rotate integers in a given list towards right and feel like I found a bug. The code that I have come up with so far is as:

def LROTR (L, n): # shifting lists to right
    n = -n%len(L)
    for i in range(0, n):
        L.append(L.pop(0))
    return L

sp0   = list(range(31, -1, -1))
print(sp0)
s0p7  = LROTR(sp0, 7)
s0p18 = LROTR(sp0, 18)

print(sp0)

The variable sp0 which is supposed to be the list before rotating, is changed for no reason after calling the LROTR function! Can someone help me figure out the issue? Is this really a bug or that's me who is mistaking python?

Using Python 3.7.0 on Windows 10 the printed output for me is:

[31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[7, 6, 5, 4, 3, 2, 1, 0, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8]

From which I expect:

[31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
PouJa
  • 180
  • 4
  • 13

1 Answers1

2

Lists are mutable: If you hand over a reference to your list to a function, that function can modify the list.

What you might want to do is give the function a copy of your list:

s0p7  = LROTR(sp0.copy(), 7)
s0p18 = LROTR(sp0.copy(), 18)
L3viathan
  • 26,748
  • 2
  • 58
  • 81