This error occurs when you pass a None value to a len() function call. NoneType objects are returned by functions that do not return anything and do not have a length.
You can solve the error by only passing iterable objects to the len() function. Also, ensure that you do not assign the output from a function that works in-place like sort() to the variable name for an iterable object, as this will override the original object with a None value
In this tutorial, we will explore the causes of this error with code examples, and you will learn how to solve the error in your code.
Table of contents
TypeError: object of type ‘NoneType’ has no len()
We raise a Python TypeError when attempting to perform an illegal operation for a specific type. In this case, the type is NoneType
.
The part ‘has no len()
‘ tells us the map object does not have a length, and therefore len()
is an illegal operation for the NoneType
object.
Retrieving the length of an object is only suitable for iterable objects, like a list
or a tuple
.
The len()
method implicitly calls the dunder method __len__()
which returns a positive integer representing the length of the object on which it is called. All iterable objects have __len__
as an attribute. Let’s check if __len__
is in the list of attributes for an NoneType
object and a list
object using the built-in dir()
method.
def hello_world(): print('Hello World') print(type(hello_world()) print('__len__' in dir(hello_world())
Hello World <class 'NoneType'> Hello World False
We can see that __len__
is not present in the attributes of the NoneType
object.
lst = ["football", "rugby", "tennis"] print(type(lst)) print('__len__' in dir(lst))
<class 'list'> True
We can see that __len__
is present in the attributes of the list
object.
Example #1: Reassigning a List with a Built-in Function
Let’s write a program that sorts a list of dictionaries of fundamental particles. We will sort the list in ascending order of the particle mass. The list will look as follows:
particles = [
{"name":"electron", "mass": 0.511},
{"name":"muon", "mass": 105.66},
{"name":"tau", "mass": 1776.86},
{"name":"charm", "mass":1200},
{"name":"strange", "mass":120}
]
Each dictionary contains two keys and values, and one key corresponds to the particle’s name, and the other corresponds to the mass of the particle in MeV. The next step involves using the sort() method to sort the list of particles by their masses.
def particle_sort(p):
return p["mass"]
sorted_particles = particles.sort(key=particle_sort)
The particle_sort function returns the value of “mass” in each dictionary. We use the mass values as the key to sorting the list of dictionaries using the sort() method. Let’s try and print the contents of the original particles list with a for loop:
for p in particles:
print("{} has a mass of {} MeV".format(p["name"], p["mass"]))
electron has a mass of 0.511 MeV
muon has a mass of 105.66 MeV
strange has a mass of 120 MeV
charm has a mass of 1200 MeV
tau has a mass of 1776.86 MeV
Let’s see what happens when we try to print the length of sorted_particles:
print("There are {} particles in the list".format(len(sorted_particles)))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-57-9b5c6f8e88b6> in <module>
----> 1 print("There are {} particles in the list".format(len(sorted_particles)))
TypeError: object of type 'NoneType' has no len()
Let’s try and print sorted_particles
print(sorted_particles)
None
Solution
To solve this error, we do not assign the result of the sort() method to sorted_particles. If we assign the sort result, it will change the list in place; it will not create a new list. Let’s see what happens if we remove the declaration of sorted_particles and use particles, and then print the ordered list.
particles.sort(key=particle_sort)
print("There are {} particles in the list".format(len(particles)))
for p in particles:
print("{} has a mass of {} MeV.".format(p["name"],p["mass"]))
There are 5 particles in the list
electron has a mass of 0.511 MeV.
muon has a mass of 105.66 MeV.
strange has a mass of 120 MeV.
charm has a mass of 1200 MeV.
tau has a mass of 1776.86 MeV.
The code now works. We see that the program prints out the number of particles in the list and the order of the particles by ascending mass in MeV.
Example #2: Not Including a Return Statement
We can put the sorting steps in the previous example in its function. We can use the same particle list and sorting function as follows:
particles = [
{"name":"electron", "mass": 0.511},
{"name":"muon", "mass": 105.66},
{"name":"tau", "mass": 1776.86},
{"name":"charm", "mass":1200},
{"name":"strange", "mass":120}
]
def particle_sort(p):
return p["mass"]
The next step involves writing a function that sorts the list using the “mass” as the sorting key.
def sort_particles_list(particles):
particles.sort(key=particle_sort)
Then we can define a function that prints out the number of particles in the list and the ordered particles by ascending mass:
def show_particles(sorted_particles):
print("There are {} particles in the list.".format(len(sorted_particles)))
for p in sorted_particles:
print("{} has a mass of {} MeV.".format(p["name"],p["mass"]))
Our program needs to call the sort_particles_list() function and the show_particles() function.
sorted_particles = sort_particles_list(particles)
show_particles(sorted_particles)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-64-65566998d04a> in <module>
----> 1 show_particles(sorted_particles)
<ipython-input-62-6730bb50a05a> in show_particles(sorted_particles)
1 def show_particles(sorted_particles):
----> 2 print("There are {} particles in the list.".format(len(sorted_particles)))
3 for p in sorted_particles:
4 print("{} has a mass of {} MeV.".format(p["name"],p["mass"]))
5
TypeError: object of type 'NoneType' has no len()
The error occurs because we did not include a return statement in the sort_particles_list() function. We assign the sort_particles_list() output to the variable sorted_particles, then pass the variable to show_particles() to get the information inside the list.
Solution
We need to add a return statement to the sort_particles_list() function to solve the error.
def sort_particles_list(particles):
particles.sort(key=particle_sort)
return particles
sorted_particles = sort_particles_list(particles)
show_particles(sorted_particles)
There are 5 particles in the list.
electron has a mass of 0.511 MeV.
muon has a mass of 105.66 MeV.
strange has a mass of 120 MeV.
charm has a mass of 1200 MeV.
tau has a mass of 1776.86 MeV.
Summary
Congratulations on reading to the end of this tutorial!
For further reading on the len() method, go to the article: How to Find the Length of a List in Python.
For further reading on the has no len()
TypeErrors, go to the article:
How to Solve Python TypeError: object of type ‘function’ has no len()
To learn more about Python for data science and machine learning, go to the online courses page on Python, which provides the best, easy-to-use online courses.
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.