python刪除list中元素的三種方法


  1. a.pop(index):刪除列表a中index處的值,並且返回這個值.
  2. del(a[index]):刪除列表a中index處的值,無返回值. del中的index可以是切片,所以可以實現批量刪除.
  3. a.remove(value):刪除列表a中第一個等於value的值,無返回.
>>> a = [0, 2, 3, 2]
>>> a.remove(2)
>>> a
[0, 3, 2]

>>> a = [3, 2, 2, 1]
>>> del a[1]
>>> a
[3, 2, 1]

>>> a = [4, 3, 5]
>>> a.pop(1)
3
>>> a
[4, 5]

#錯誤信息也不一樣
>>> a = [4, 5, 6]
>>> a.remove(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del a[7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
>>> a.pop(7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM