John Doe
John Doe

Reputation: 181

Removing a string from a list

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

Ex:

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

What am I doing wrong here? All I want is 'c' to be removed from myList!

Upvotes: 5

Views: 34037

Answers (4)

Cody Stevens
Cody Stevens

Reputation: 414

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.

Upvotes: 1

Hrishikesh
Hrishikesh

Reputation: 345

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')

Upvotes: 0

Anand S Kumar
Anand S Kumar

Reputation: 90889

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

Upvotes: 21

MrAlexBailey
MrAlexBailey

Reputation: 5289

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

Upvotes: 5

Related Questions