列表list:list是一种有序的集合,可以随时添加和删除其中的元素。
一、添加元素
list1=[1,2,3]
1、list.append():
往list中追加元素到末尾
list1.append(5)
list1=[1, 2, 3, 5]
2、list.insert(i, 'str'):
把元素插入到指定的位置,比如索引号为i的位置
list1.insert(2,4)
list1=[1, 2, 4,3, 5]
二、删除元素
list1=[1,2,3]
1、list.pop():
删除list末尾的元素
list1.pop()
list1=[1,2]
2、list.pop(i)
删除指定位置的元素,用pop(i)方法,其中i是索引位置
list1.pop(0)
list1=[2]
3、list.remove()
删除指定元素
list1=[1,2,3]
list1.remove(3)
list1=[1,2]
*******************************************************************************************************************
Python对于列表的del, remove, pop操作的区别
1、remove 是删除首个符合条件的元素。并不是删除特定的索引。如下例:
>>> a = [0, 2, 2, 3]
>>> a.remove(2)
>>> a
[0, 2, 3]
2、 del 是根据索引(元素所在位置)来删除的,如下例:
>>> a = [3, 2, 2, 1]
>>> del a[1]
>>> a = [3, 2, 2, 1]
>>> del a[1]
[3, 2, 1]
第1个元素为a[0] --是以0开始计数的。则a[1]是指第2个元素,即里面的值2.
del还可以删除指定范围内的值
a = [3,2,2,1]
del a[1,3]
print a
结果[3]
del还可以删除整个列表
del a
3、pop返回的是你弹出的那个数值。
>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]
所以使用时要根据你的具体需求选用合适的方法
注: Python对于列表的del, remove pop操作的区别
引自:stackoverflow Q11520492
http://novell.me/master-diary/2014-06-05/difference-between-del-remove-and-pop-on.html