>>> a = [0, 1, 2, 3]
>>> a.pop() # 弹末尾
3
>>> a
[0, 1, 2]
>>> a.pop(0) # 按索引弹
0
>>> a
[1, 2]
>>> a.pop(10) # 索引超标,抛出异常
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
a.pop(10)
IndexError: pop index out of range
>>>
说明
在原列表的基础上直接操作
remove()
>>> a = [1, 2, 3, 2, 1]
>>> a.remove(2)
>>> a
[1, 3, 2, 1]
>>> a.remove(10)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a.remove(10)
ValueError: list.remove(x): x not in list
>>>
说明
在原列表的基础上直接操作
从头遍历,移除第一个
没有找到,抛出异常
clear()
>>> a = [0, 1, 2, 3]
>>> a.clear()
>>> a
[]
>>>
del
>>> a = [0, 1, 2, 3]
>>> del a
>>> a
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
a
NameError: name 'a' is not defined
>>>
reverse()
>>> a = [0, 1, 2, 3]
>>> a.reverse()
>>> a
[3, 2, 1, 0]
>>>
sort()
>>> a = [1, 3, 5, 2, 4, 6]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5, 6]
>>> a.sort(reverse=True)
>>> a
[6, 5, 4, 3, 2, 1]
>>>
count()
>>> a = [1, 2, 3, 2, 1]
>>> a.count(1)
2
>>>
len()
>>> a = [1, 2, 3, 4, 5]
>>> len(a)
5
>>>
说明
len(list) 是 O(1) 的,不像 C 那样每次都要重新遍历,因为 list 有块记录长度的空间
index()
>>> a = ['1', '2', '3', '2', '1']
>>> a.index('2')
1
>>> a.index('2', 2)
3
>>> a.index('5')
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a.index('5')
ValueError: '5' is not in list
>>>
copy()
>>> a = [0, 1, 2, 3]
>>> b = a.copy()
>>> id(a)
2113228704064
>>> id(b)
2113228640128
>>> a[0] = 10
>>> a
[10, 1, 2, 3]
>>> b
[0, 1, 2, 3]
>>>
>>> c = [0, 1, [2, 3]]
>>> d = a.copy()
>>> c[2][0] = 20
>>> c
[0, 1, [20, 3]]
>>> d
[0, 1, [20, 3]]
>>>
说明
copy() 只能管第一层
若想“深拷贝”,需要 from copy import deepcopy, b = deepcopy(a)