I've written this function to take a list and shift each member right by the number supplied as the offset.
I want to preserve the supplied list and return the shifted list.
My problem is that the function modifies the supplied input list itself as well as returning a new list with the elements shifted, but I can't figure out why. I need the supplied list to be unchanged.
My debugging shows me that the line:
work[i + offset] = list_in[i]
is the culprit because each time it executes, the supplied input list changes as well.
I'm stumped as to why. Any ideas?
Here's the function:
def shift_right(list_in, offset):
"""
Shifts list to the right by number supplied as offset
"""
# We want to preserve the supplied list, so make a copy
work = list_in
# Check that offset doesn't exceed length of list
# if it does return 1 as error code
if offset >= len(list_in):
return "1"
else:
if len(list_in) > 0:
# capture fall off to the right to
# be re-inserted at beginning of list
hold = list_in[offset + 1:]
# now begin the shifting
for i in range(len(list_in)-offset):
work[i + offset] = list_in[i]
# Now take the values that fell off and put them
# back at the beginning
else:
for x in range(len(hold)):
work[x] = hold[x]
return work
# Test the function
one = [1,2,3,4,5,6,7]
print(shift_right(one, 3))
The result I get is [5, 6, 7, 1, 2, 3, 1]