How to remove an element from a list by index

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

提交回复
热议问题