【Python】Python -移除List內的items。Remove List Items
【Python】Python -移除List內的items。Remove List Items
移除特定的Item
The remove() method 可以移除特定的Item。
範例
移除 "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)上面輸出:['apple', 'cherry']移除使用特定的index
The pop() method 可以移除特定index number的item。
範例
移除第二個item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)上面輸出:['apple', 'cherry']如果不指定index, 則pop()方法會移除最後一個item。
Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)上面輸出:['apple', 'banana']The del keyword 也會移除特定的index:
範例
移除第一個item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)上面輸出:['banana', 'cherry']The del keyword 可以刪除整個list。
範例
刪除整個list:
thislist = ["apple", "banana", "cherry"]
del thislistprint(thislist)上面輸出:Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'thislist' is not defined上面表示:整個list都被從記憶體刪除,所以秀出沒有定義。清除List
The clear() method 清空list.
但list仍舊存在記憶體內,沒有消失
範例
清除list內的所有內容:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)上面輸出:[]沒有錯誤訊息,只是list內是空的‧

留言
張貼留言