刷leetcode时,题目“翻转数组”下发现一个问题:
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
k %= len(nums)
nums[:] = nums[-k:] + nums[:-k]
而最后一句当我用nums = nums[-k:] + nums[:-k],就会出错。
原因是新建了一个与参数重名的局部变量,而使用nums[:]就可以,原理是什么呢。
我又试了一下如下代码
a = [1, 2, 3]
print(id(a))
print(id(a[:]))
a = [4, 5, 6]
print(id(a))
print(id(a[:]))
print(a)
输出是这样的
2284479734280
2284479734344
2284479734344
2284479734280
[4, 5, 6]
想请教一下nums和nums[:]的区别。感谢!