I imagine there is a simple solution that I am overlooking. Better that than a complicated one, right?
Simply put:
var = ['p', 's', 'c', 'x', 'd'].remove('d')
causes var
to be of type None
. What is going on here?
The 'NoneType' object is not an iterable error and is not generated if you have any empty list or a string. Technically, you can prevent the NoneType exception by checking if a value is equal to None using is operator or == operator before you iterate over that value.
The remove() method does not return the value that has been removed but instead just returns None , meaning there is no return value.
The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.
The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item. You can also use the del keyword in Python to remove an element or slice from a list.
remove
doesn't return anything. It modifies the existing list in-place. No assignment needed.
Replace
var = ['p', 's', 'c', 'x', 'd'].remove('d')
with
var = ['p', 's', 'c', 'x', 'd']
var.remove('d')
Now var
will have a value of ['p', 's', 'c', 'x']
.
remove
mutates the list in-place, and returns None
. You have to put it in a variable, and then change that:
>>> var = ['p', 's', 'c', 'x', 'd']
>>> var.remove('d') # Notice how it doesn't return anything.
>>> var
['p', 's', 'c', 'x']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With