如何从列表中删除第一个项?
[0, 1, 2, 3] → [1, 2, 3]
对我来说这个方法很有效,不要像下面那样使用pop
,因为pop
的结果/返回值当然是0。
>>> x = [0, 1, 2, 3].pop(0)
>>> x
0
>>> x = [0, 1, 2, 3][1:]
>>> x
[1, 2, 3]
lst = [0, 1, 2, 3]
lst[:1] = []
print(lst) # [1, 2, 3]
list.pop()
不同,即使列表为空,切片操作也不会引发IndexError,这在某些情况下很有用(而在其他情况下则无用)。lst = []
lst.pop(0) # <--- IndexError
del lst[:1] # <--- no error
lst[:] = lst[1:] # <--- no error
lst[:1] = [] # <--- no error