简体   繁体   中英

Unable to modify Python List in-place from within Function

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

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)      

The line:

nums = a + b

You have to use inplace-methods on your list, eg del<\/code> and extend<\/code> :

def rotate(nums, k):
    a = nums[:-k]
    del nums[:-k]
    nums.extend(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM