刪除串列或元素

  1. 刪除第 i+1 個元素、每隔 step,第 start+1 到 end 個元素,step 不指定則預設為 1。
    del listx[i]
    del listx[start:end]
    del listx[start:end:step]
    
  2. 範例:刪除串列 listx 第 4 個元素、再刪除第 6 到 6 個元素,再每隔 2,刪除第 3 到 8 個元素。
    [dywang@deyu zzz]$ cat list8.py
    #!/usr/bin/python3
    # coding: utf-8
    
    listx = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ]
    print("listx =", listx)
    del listx[3]
    print("listx =", listx)
    del listx[5:6]
    print("listx =", listx)
    del listx[2:8:2]
    print("listx =", listx)
    
  3. 執行結果
    [dywang@deyu zzz]$ ./list8.py
    listx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    listx = [1, 2, 3, 5, 6, 7, 8, 9, 0]
    listx = [1, 2, 3, 5, 6, 8, 9, 0]
    listx = [1, 2, 5, 8, 0]
    
  4. 範例:刪除整個串列 listx。
    [dywang@deyu zzz]$ cat list9.py 
    #!/usr/bin/python3
    # coding: utf-8
    
    listx = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 ]
    print("listx =", listx)
    del listx
    print("listx =", listx)
    
  5. 執行結果:刪除後 listx 不存在,不是變成空串列。
    [dywang@deyu zzz]$ ./list9.py 
    listx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
    listx = 
    Traceback (most recent call last):
      File "./list9.py", line 7, in <module>
        print("listx = ", listx)
    NameError: name 'listx' is not defined