The built-in function len() only works on iterable objects such as strings, lists, and dictionaries. These iterable objects contain sequences of values and therefore have a length. If you try to use the len() function a None type value, you will raise the error: TypeError: object of type ‘NoneType’ has no len().

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.


TypeError: object of type ‘NoneType’ has no len()

Let’s break up the error into parts to understand the problem exactly. TypeError is an error we raise when performing an illegal operation for a specific data type.

Another common example of this error is TypeError: ‘int’ object is not subscriptable, which tells us we do subscriptable operations on integer objects, because they do not contain other objects, like a list.

The part “object of type” tells us that the object is of None type. The part “has no len()” tells us the None type does not support the built-in function len() because it does not contain a collection of values.

i = None
print(len(i))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-47-846941af8d1e> in <module>
----> 1 print(len(i))

TypeError: object of type 'NoneType' has no len()

Common mistakes that can cause this error is:

  • Reassigning a list with a built-in function
  • Forgetting to include a return statement in a function

Let’s go through each of these mistakes and find the solutions for them.

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. The TypeError: object of type ‘NoneType’ has no len() occurs when you attempt to use the len() function on a None type object. To solve this error, ensure you do not change the list in place with the response of one of the built-in list functions, like sort(). If you call one of the built-in functions, you do not need to assign the response to a new variable. You also need to ensure all you include all necessary return statements in the functions within your code.

For further reading on the len() method, go to the article: How to Find the Length of a List in Python.

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.