Python中的数组是按值分配还是按引用分配?

问题描述:

我想知道为什么删除原始数组会影响复制的数组:

I am wondering why when I delete the original array it affects the copied array:

arr = [1,2,3]
arr1 = arr
del arr[:]
print(arr1) #this prints []

但是当我修改原始数组的元素时,对复制的数组没有影响:

but when I modify the elements of the original array there is no effect on the copied array:

arr = [1,2,3]
arr1 = arr
arr = [4,5,6]
print(arr1) #this prints [1,2,3]

如果有人可以解释这个问题,谢谢您的帮助.

If someone can explain this issue I appreciate your help, thanks in advance.

您没有修改原始数组的元素,而是将新列表重新分配给 arr 变量.如果您正确访问元素的元素,您对元素更改的直觉将反映在 arr1 中,因为Python中的列表是 mutable .例如,

You did not modify the elements of the original array, but rather re-assigned a new list to the arr variable. Your intuition of thinking changes to elements would be reflected in arr1 if you properly accessed its elements is indeed true as lists are mutable in Python. For instance,

arr = [1,2,3]
arr1 = arr
arr[1] = 4
print(arr1) #this prints [1,4,3]