list = [element] + list 创建一个新列表并覆盖原来的值,嗯,list。我没有将 element 添加到现有列表中,因此它不会演示通过引用传递。相当于:
list2 = [element] + list
list = list2
以下演示通过添加到现有列表而不是创建新列表来传递引用。
def prepend(element, _list):
_list.insert(0, element)
_try = [1,2,3]
prepend(0, _try)
print(_try)
更新
如果我添加显示变量在程序执行时如何变化的打印语句,可能会更清楚。 prepend 有两种版本,一种用于创建新对象,另一种用于更新现有对象。 id() 函数返回对象的唯一标识符(在 cpython 中为对象的内存地址)。
def prepend_1(element, _list):
print 'prepend_1 creates a new list, assigns it to _list and forgets the original'
print '_list refers to the same object as _try -->', id(_list), _list
_list = [element] + _list
print '_list now refers to a different object -->', id(_list), _list
def prepend_2(element, _list):
print 'prepend_2 updates the existing list'
print '_list refers to the same object as _try -->', id(_list), _list
_list.insert(0, element)
print '_list still refers to the same object as _try -->', id(_list), _list
_try = [1,2,3]
print '_try is assigned -->', id(_try), _try
prepend_1(0, _try)
print '_try is the same object and is not updated -->', id(_try), _try
prepend_2(0, _try)
print '_try is the same object and is updated -->', id(_try), _try
print _try
当我运行它时,你可以看到对象与引用它们的变量之间的关系
_try is assigned --> 18234472 [1, 2, 3]
prepend_1 creates a new list, assigns it to _list and forgets the original
_list refers to the same object as _try --> 18234472 [1, 2, 3]
_list now refers to --> 18372440 [0, 1, 2, 3]
_try is the same object and is not updated --> 18234472 [1, 2, 3]
prepend_2 updates the existing list
_list refers to the same object as _try --> 18234472 [1, 2, 3]
_list still refers to the same object as _try --> 18234472 [0, 1, 2, 3]
_try is the same object and is updated --> 18234472 [0, 1, 2, 3]
[0, 1, 2, 3]