列表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