How to remove an element from a list by index

后端 未结 18 2942
闹比i
闹比i 2020-11-22 03:22

How do I remove an element from a list by index in Python?

I found the list.remove method, but say I want to remove the last element, how do I do this?

18条回答
  •  别那么骄傲
    2020-11-22 03:49

    Yet another way to remove an element(s) from a list by index.

    a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    # remove the element at index 3
    a[3:4] = []
    # a is now [0, 1, 2, 4, 5, 6, 7, 8, 9]
    
    # remove the elements from index 3 to index 6
    a[3:7] = []
    # a is now [0, 1, 2, 7, 8, 9]
    

    a[x:y] points to the elements from index x to y-1. When we declare that portion of the list as an empty list ([]), those elements are removed.

提交回复
热议问题