"TypeError: object of type 'NoneType' has no len()" after using remove() on a list
Question:
I have this code:
list_of_directions = ['right', 'left', 'up', 'down']
new_list = list_of_directions.remove('right')
print(len(new_list))
But I get the error message
TypeError: object of type ‘NoneType’ has no len()
I thought I understood how .remove()
works, but maybe I don’t?
Why do I get this error?
Answers:
list.remove
is an in-place operation. It returns None
.
You need to perform this operation in a separate line to new_list
. In other words, instead of new_list = list_of_directions.remove('right')
:
new_list = list_of_directions[:]
new_list.remove('right')
In the above logic, we assign new_list
to a copy of list_of_directions
before removing a specific element.
Notice the importance of assigning to a copy of list_of_directions
. This is to avoid the highly probable scenario of new_list
changing with list_of_directions
in an undesired manner.
The behaviour you are seeing is noted explicitly in the docs:
You might have noticed that methods like insert
, remove
or sort
that only modify the list have no return value printed – they return
the default None
. This is a design principle for all mutable data
structures in Python.
I have this code:
list_of_directions = ['right', 'left', 'up', 'down']
new_list = list_of_directions.remove('right')
print(len(new_list))
But I get the error message
TypeError: object of type ‘NoneType’ has no len()
I thought I understood how .remove()
works, but maybe I don’t?
Why do I get this error?
list.remove
is an in-place operation. It returns None
.
You need to perform this operation in a separate line to new_list
. In other words, instead of new_list = list_of_directions.remove('right')
:
new_list = list_of_directions[:]
new_list.remove('right')
In the above logic, we assign new_list
to a copy of list_of_directions
before removing a specific element.
Notice the importance of assigning to a copy of list_of_directions
. This is to avoid the highly probable scenario of new_list
changing with list_of_directions
in an undesired manner.
The behaviour you are seeing is noted explicitly in the docs:
You might have noticed that methods like
insert
,remove
orsort
that only modify the list have no return value printed – they return
the defaultNone
. This is a design principle for all mutable data
structures in Python.