Search code examples
pythonpython-3.xin-place

Unable to modify Python List in-place from within Function


We have a function rotate() that takes a list nums and modifies it in-place. However I am unable to get the correctly modified list from after the rotate() function call.

Why is this happening?

def rotate(nums, k):
    """
    Rotate the list to the right by k steps
    Do not return anything, modify nums in-place instead.
    """

    # Reverse
    nums.reverse()
    a = nums[:k]
    a.reverse()
    b = nums[-(len(nums)-k):]
    b.reverse()
    nums = a + b
    print('Inside function:', nums)

nums = [1,2,3,4,5,6]
rotate(nums, 3)
print('Outside function: ', nums)      

Output

Inside function: [4, 5, 6, 1, 2, 3]
Outside function:  [6, 5, 4, 3, 2, 1]   <--- incorrect!

Solution

  • The line:

    nums = a + b
    

    Creates a new local variable nums in the scope of your rotate function. To modify the list as passed in, you can change that line to the following:

    nums[:] = a + b