"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?

Asked By: Addison

||

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.

Answered By: jpp
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.