1. del 函數刪除引用,並不是對象 (如下代碼是直接運行在Ipython console下)html
#spyder: example 1 xx = [1,2,3] #賦值 xx #輸出xx Out[2]: [1, 2, 3] del xx #刪除引用,但未刪除對象 xx #輸出xx,報錯 Traceback (most recent call last): File "<ipython-input-4-ce3af7760f12>", line 1, in <module> xx NameError: name 'xx' is not defined
#spyder: example 2 xx = [1,2,3] yy = xx xx Out[7]: [1, 2, 3] yy Out[8]: [1, 2, 3] del xx xx #輸出xx報錯 Traceback (most recent call last): File "<ipython-input-10-ce3af7760f12>", line 1, in <module> xx NameError: name 'xx' is not defined yy #輸出yy Out[11]: [1, 2, 3] # 參考:https://www.cnblogs.com/xisheng/p/7340514.html
2. list刪除元素的方法(del函數和remove函數)python
# del函數
test_list = [1, 2, '故事','story',3] del test_list[0] #索引刪除:刪除第一個元素 print(test_list) #輸出:[2, '故事', 'story', 3] test_list = [1, 2, '故事','story',3] del test_list[0:2] #索引刪除:刪除第[0:2]的元素 print(test_list) #輸出:['故事', 'story', 3] # remove函數 test_list = [1, 2, '故事','story',3] test_list.remove('story') #元素直接刪除 print(test_list) #輸出:[1, 2, '故事', 3]