Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 519
John Doe Avatar asked May 07 '26 14:05

John Doe


2 Answers

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

like image 72
Anand S Kumar Avatar answered May 09 '26 02:05

Anand S Kumar


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

like image 37
MrAlexBailey Avatar answered May 09 '26 04:05

MrAlexBailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!