How to remove an element from a list by index

后端 未结 18 2941
闹比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 04:05

    It doesn't sound like you're working with a list of lists, so I'll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it's "-1"

    >>> test = ['item1', 'item2']
    >>> test.pop(-1)
    'item2'
    >>> test
    ['item1']
    

提交回复
热议问题