Removing a string from a list

后端 未结 4 823
抹茶落季
抹茶落季 2021-01-16 04:04

I create a list, and I want to remove a string from it.

Ex:

>>> myList = [\'a\', \'b\', \'c\', \'d\']   
>>> myList = myList.remove         


        
相关标签:
4条回答
  • 2021-01-16 04:34

    Remember that lists are mutable, so you can simply call remove on the list itself:

    >>> myList = ['a', 'b', 'c', 'd']
    >>> myList.remove('c')
    >>> myList
    ['a', 'b', 'd']
    

    The reason you were getting None before is because remove() always returns None

    0 讨论(0)
  • 2021-01-16 04:35

    Just an addition to Anand's Answer,

    mylist = mylist.remove('c')
    

    The above code will return 'none' as the return type for my list. So you want to keep it as

    mylist.remove('c')
    
    0 讨论(0)
  • 2021-01-16 04:46

    I am not sure what a is (I am guessing another list), you should do myList.remove() alone, without assignment.

    Example -

    >>> myList = ['a', 'b', 'c', 'd']
    >>> myList.remove('c')
    >>> myList
    ['a', 'b', 'd']
    

    myList.remove() does not return anything, hence when you do myList = <anotherList>.remove(<something>) it sets myList to None

    0 讨论(0)
  • 2021-01-16 04:49

    The remove() function doesn't return anything, it modifies the list in place. If you don't assign it to a variable you will see that myList doesn't contain c anymore.

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