python中有3個刪除元素的方法:del remove pop
雖然它們都是刪除元素,用於刪除列表、字符串等里面的元素,但是用法可不完全一樣,元組由於是不可變的,所以不能使用哦!那么接下來就來看看它們之間有什么區別:
# 代碼源列表如下:
a_list = ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']
1. del——指定索引值刪除
# del 列表[索引值]
del a_list[1]
# 源列表:
['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python']
# del刪除數據后的列表:
['Mecell', 'Python', True, None, [1, 2, 3], 'Python']
2. remove——默認移除第一個出現的元素
# 列表.remove[刪除對象] # 對象可以是列表里面的任何數據類型:字符串、數字、bool等 a_list.remove['Python'] # 源列表: ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python'] # remove刪除數據后的列表: ['Mecell', 18, True, None, [1, 2, 3], 'Python'] 從結果可以看出,列表里面有兩個'Python',但是實際上只是刪除了第一個,最后一個並沒有刪除,這就是remove的特點,需要大家注意!
3. pop——括號內不添加索引值,則默認刪除列表中的最后一個元素;反之則默認根據索引值刪除
# 列表.pop() --刪除最后一個元素 a_list.pop() # 源列表: ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python'] # pop刪除數據后的列表: ['Mecell', 18, 'Python', True, None, [1, 2, 3]] # 列表.pop(索引值) --指定索引值刪除 a_list.pop(3)
# 源列表: ['Mecell', 18, 'Python', True, None, [1, 2, 3], 'Python'] # pop刪除數據后的列表: ['Mecell', 18, 'Python', None, [1, 2, 3], 'Python']
以上就是del,remove和pop的用法區別啦!