共同点:都是尝试删除列表中的指定某一个内容。
区别:
对于列表可以用pop(),del(),remove(),
- pop(index) 弹出/删除指定位置的内容,默认参数为-1,即弹出最后一个。返回弹出内容。
使用方式为:arr.pop(index),索引超出会报’IndexError: pop index out of range’。 - del() 指定列表名与序号,无返回值;
使用方式为:del(arr[2]) ,索引超出会报’IndexError: list assignment index out of range’ - remove() 删除指定内容,无返回值。
使用方式为:arr.remove(item),item不存在则报’ValueError: list.remove(x): x not in list’
>>> arr = ['a', 'b', 'c']
>>> # 正常使用,无返回值输出
>>> arr.remove('a')
>>> # 异常,报错
>>> arr.remove('X')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> arr = ['a', 'b', 'c']
>>> # 正常使用,无返回值输出
>>> del(arr[1])
>>> # 超出范围,报错
>>> del(arr[10])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> arr = ['a', 'b', 'c']
>>> # 正常使用,有返回值输出
>>> arr.pop(1)
'b'
>>> # 超出范围,报错
>>> arr.pop((10))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
对于字典:
- √ 可以使用pop() 弹出指定key,有返回值,无key则报‘AttributeError’。
- √ 使用del(dic[key]) 删除指定dic的指定key的内容,无key则报‘KeyError: ’。
- × remove(key) 字典中没有remove方法。