Python对于列表的del, remove, pop操作的区别

来源:互联网 发布:数据库视频教程 编辑:程序博客网 时间:2024/05/16 07:53

首先,remove 是删除首个符合条件的元素。并不是删除特定的索引。如下例:

  1. >>> a = [0223
  2. >>> a.remove(2
  3. >>> a 
  4. [023]
而对于 del 来说,它是根据索引(元素所在位置)来删除的,如下例:

  1. >>> a = [3221
  2. >>> del a[1
  3. [321
        第1个元素为a[0] --是以0开始计数的。则a[1]是指第2个元素,即里面的值2.

        del还可以删除指定范围内的值

        a = [3,2,2,1]

        del a[1,3]

        print a

        结果[3]


        del还可以删除整个列表

        del a


pop返回的是你弹出的那个数值。

所以使用时要根据你的具体需求选用合适的方法


  1. >>> a = [435
  2. >>> a.pop(1
  3. 3 
  4. >>> a 
  5. [45]

另外它们如果出错,出错模式也是不一样的。注意看下面区别:

  1. >>> a = [456
  2. >>> a.remove(7
  3. Traceback (most recent call last): 
  4.   File "<stdin>", line 1in <module> 
  5. ValueError: list.remove(x): x not in list 
  6. >>> del a[7
  7. Traceback (most recent call last): 
  8.   File "<stdin>", line 1in <module> 
  9. IndexError: list assignment index out of range 
  10. >>> a.pop(7
  11. Traceback (most recent call last): 
  12.   File "<stdin>", line 1in <module> 
  13. IndexError: pop index out of range
注:本文引自stackoverflow  Q11520492

http://novell.me/master-diary/2014-06-05/difference-between-del-remove-and-pop-on.html

0 0
原创粉丝点击