Python中的数组是按值分配还是按引用分配? [英] Arrays in Python are assigned by value or by reference?

查看:84
本文介绍了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]

这篇关于Python中的数组是按值分配还是按引用分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆