Remove list element without mutation

后端 未结 6 1375
无人及你
无人及你 2021-02-04 23:36

Assume you have a list

>>> m = [\'a\',\'b\',\'c\']

I\'d like to make a new list n that has everything except for a given

6条回答
  •  既然无缘
    2021-02-05 00:19

    I assume you mean that you want to create a new list without a given element, instead of changing the original list. One way is to use a list comprehension:

    m = ['a', 'b', 'c']
    n = [x for x in m if x != 'a']
    

    n is now a copy of m, but without the 'a' element.

    Another way would of course be to copy the list first

    m = ['a', 'b', 'c']
    n = m[:]
    n.remove('a')
    

    If removing a value by index, it is even simpler

    n = m[:index] + m[index+1:]
    

提交回复
热议问题