How to remove an element from a list by index

后端 未结 18 2810
闹比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:45

    If you want to remove the specific position element in a list, like the 2th, 3th and 7th. you can't use

    del my_list[2]
    del my_list[3]
    del my_list[7]
    

    Since after you delete the second element, the third element you delete actually is the fourth element in the original list. You can filter the 2th, 3th and 7th element in the original list and get a new list, like below:

    new list = [j for i, j in enumerate(my_list) if i not in [2, 3, 7]]
    
    0 讨论(0)
  • 2020-11-22 03:46

    l - list of values; we have to remove indexes from inds2rem list.

    l = range(20)
    inds2rem = [2,5,1,7]
    map(lambda x: l.pop(x), sorted(inds2rem, key = lambda x:-x))
    
    >>> l
    [0, 3, 4, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
    
    0 讨论(0)
  • 2020-11-22 03:46

    Use the del statement:

    del listName[-N]
    

    For example, if you want to remove the last 3 items, your code should be:

    del listName[-3:]
    

    For example, if you want to remove the last 8 items, your code should be:

    del listName[-8:]
    
    0 讨论(0)
  • 2020-11-22 03:47

    You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.

    >>> a=[1,2,3,4,5]
    >>> del a[1]
    >>> a
    [1, 3, 4, 5]
    >>> a.pop(1)
     3
    >>> a
    [1, 4, 5]
    >>> 
    
    0 讨论(0)
  • 2020-11-22 03:49

    This depends on what you want to do.

    If you want to return the element you removed, use pop():

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

    However, if you just want to delete an element, use del:

    >>> l = [1, 2, 3, 4, 5]
    >>> del l[2]
    >>> l
    [1, 2, 4, 5]
    

    Additionally, del allows you to use slices (e.g. del[2:]).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题