Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing item from list causes the list to become NoneType

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?

like image 764
Joseph_Renerr Avatar asked Nov 05 '14 20:11

Joseph_Renerr


People also ask

Is an empty list a NoneType object?

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.

Does remove Return none in Python?

The remove() method does not return the value that has been removed but instead just returns None , meaning there is no return value.

How do I get rid of NoneType in Python?

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.

What function removes an item from a list?

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.


2 Answers

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'].

like image 160
Kevin Avatar answered Oct 20 '22 15:10

Kevin


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']
like image 39
anon582847382 Avatar answered Oct 20 '22 16:10

anon582847382