>>> x = 1
>>> del x
>>> x
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
x
NameError: name ‘x‘ is not defined
>>> x = [‘Hello‘,‘world‘]
>>> y = x
>>> y
[‘Hello‘, ‘world‘]
>>> x
[‘Hello‘, ‘world‘]
>>> del x
>>> x
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
x
NameError: name ‘x‘ is not defined
>>> y
[‘Hello‘, ‘world‘]
>>>
可以看到x和y指向同一个列表,但是删除x后,y并没有受到影响。这是为什么呢?
The reason for this is that you only delete the name,not the list itself,In fact ,there is no way to delete values in python(and you don’t really need to because the python interpreter does it by itself whenever you don’t use the value anymore)
举个例子,一个数据(比如例子中的列表),就是一个盒子,我们把它赋给一个变量x,就是好像把一个标签x贴到了盒子上,然后又贴上了y,用它们来代表这个数据,但是用del删除这个变量x就像是把标有x的标签给撕了,剩下了y的标签。
再看一个例子:
shoplist = [‘apple‘, ‘mango‘, ‘carrot‘, ‘banana‘]
print (‘The first item I will buy is‘, shoplist[0])
olditem = shoplist[0]
del shoplist[0] #del的是引用,而不是对象
print (‘I bought the‘,olditem)
print (‘My shopping list is now‘, shoplist)
print(shoplist[0])
结果为:
The first item I will buy is apple
I bought the apple
My shopping list is now [‘mango‘, ‘carrot‘, ‘banana‘]
mango