How to remove an element from a list by index

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

提交回复
热议问题