1

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!
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830

2 Answers2

4

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
pault
  • 41,343
  • 15
  • 107
  • 149
1

You have to use inplace-methods on your list, e.g. del and extend:

def rotate(nums, k):
    a = nums[:-k]
    del nums[:-k]
    nums.extend(a)
Daniel
  • 42,087
  • 4
  • 55
  • 81