Typeerror object of type nonetype has no len ошибка

I keep getting this error

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

here is the code:

def main():
    myList = [ ]
    myList = read_csv()
    ## myList = showList(myList)
    searchList = searchQueryForm(myList)
    if len(searchList) == 0:
        print("I have nothing to print")
    else:
        showList(searchList)

Mureinik's user avatar

Mureinik

295k52 gold badges303 silver badges346 bronze badges

asked May 19, 2015 at 8:48

Rasnaam Tiwana's user avatar

3

searchQueryForm apparently returns a None if it finds nothing. Since you can’t apply len to None, you’ll have to check for that explicitly:

if searchList is None or len(searchList) == 0:

answered May 19, 2015 at 8:53

Mureinik's user avatar

MureinikMureinik

295k52 gold badges303 silver badges346 bronze badges

0

The object which you want to get the len() from is obviously a None object.

It is the searchList, returned from searchQueryForm(myList).

So this is None when it shouldn’t be.

Either fix that function or live with the fact that it can return None:

if len(searchlist or ()) == 0:

or

if not searchlist:

answered May 19, 2015 at 8:53

glglgl's user avatar

glglglglglgl

88.6k13 gold badges148 silver badges217 bronze badges

The searchQueryForm() function return None value and len() in-build function not accept None type argument. So Raise TypeError exception.

Demo:

>>> searchList = None
>>> print type(searchList)
<type 'NoneType'>
>>> len(searchList)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: object of type 'NoneType' has no len()

Add one more condition in if loop to check searchList is None or not

Demo:

>>> if searchList==None or len(searchList) == 0:
...   print "nNothing"
... 
nNothing

return statement is missing in the searchQueryForm() function when code is not go into last if loop. By default None value is return when we not return any specific value from function.

def searchQueryForm(alist):
    noforms = int(input(" how many forms do you want to search for? "))
    for i in range(noforms):
        searchQuery = [ ]
        nofound = 0 ## no found set at 0
        formname = input("pls enter a formname >> ") ## asks user for formname
        formname = formname.lower() ## converts to lower case
        for row in alist:
            if row[1].lower() == formname: ## formname appears in row2
                searchQuery.append(row) ## appends results
                nofound = nofound + 1 ## increments variable
                if nofound == 0:
                    print("there were no matches")
                    return searchQuery
    return []
   # ^^^^^^^    This was missing 

answered May 19, 2015 at 8:55

Vivek Sable's user avatar

Vivek SableVivek Sable

9,8503 gold badges38 silver badges55 bronze badges

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()
  • Example #1: Reassigning a List with a Built-in Function
    • Solution
  • Example #2: Not Including a Return Statement
    • Solution
  • Summary

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.

The

len()

is an inbuilt Python function that returns the total number of elements or characters present in an iterable object, such as string, list, tuple, set, or dictionary. And if we try to perform the

len()

function on a non-iterable object like None, there, we will encounter the error »

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

«.

In this Python error debugging tutorial, we will discuss why this error occurs in a Python program and how to solve it. To learn this error in detail, we will also walk through some common example scenarios, so you can solve the error for yourself.

So without further ado, let’s get started with the error statement itself.

In Python, every data value has a data type that we can find using the type() function. The integer values like 1, 2, 3, etc., have a data type of

int

, floating-point numbers 1.0, 2.3, 4.34, etc. have the data type of

float

. Similarly, the

None

value data type is

NoneType

. We can confirm it using the type function.

>>> type(None)
<class 'NoneType'>

Now let’s take a look at the error statement. The error statement

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

has two parts.


  1. TypeError

  2. object of type ‘NoneType’ has no len()

TypeError

TypeError is one of the most common Python standard exceptions. It is raised in a Python program when we perform an invalid or unsupported operation on a Python data object.

object of type ‘NoneType’ has no len()

The statement »

object of type 'NoneType' has no len()

» is the error message telling us that the data type ‘

NoneType

‘ does not support the

len()

function.

Error Reason

We only get this error in a Python program when we pass a None value as an argument to the len() function.


Example

value = None

print(len(value))


Output

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


Common Example Scenario

Now we know why this error occurs in a Python program, let’s discuss some common example scenarios where many python learners encounter this error.

  1. Reassign the list with None returning methods.
  2. Forget to mention the return statement in a function.

1. Reassign the list with None returning Method

There are many methods in the list that perform the in-place operations and return None. And often, when we do not have a complete idea about the return value of the

list methods

, we assign the returned

None

value to the list name and perform the

len()

operation on the newly assigned value, and receive the error.


Error Example

Let’s say we have a list


bucket


that contains the name of some items, and we want to sort that list in alphabetical order.

bucket = ["Pen", "Note Book", "Paper Clip", "Paper Weight", "Marker"]

# sort the bucket 
bucket = bucket.sort()   #None

items = len(bucket)
print("There are total", items, "items in your bucket")

for item in bucket:
	print(item)


Output

Traceback (most recent call last):
  File "main.py", line 6, in 
    items = len(bucket)
TypeError: object of type 'NoneType' has no len()

In the above example, we are receiving the with the statement

len(bucket)

. This is because in line 4, where we have sorted the list »

bucket

» there, we have also assigned the

bucket.sort()

to

bucket

.

The list

sort()

method performs the in-place sorting and returns

None

as a value.  And when we assigned the

sort()

method’s returned value to

bucket

in line 4, where the value of the

bucket

became

None

. Later, when Python tries to perform the

len()

function on the

None

bucket value, Python raises the error.

Solution

For those methods that perform an in-place operation such as

sort()

we do not need to assign their return value to the list identifier. To solve the above problem, all we need to take care of is that we are not assigning the value returned by the list sort() method.

bucket = ["Pen", "Note Book", "Paper Clip", "Paper Weight", "Marker"]

# sort the bucket 
bucket.sort()  

items = len(bucket)
print("There are total", items, "items in your bucket")

for item in bucket:
	print(item)


Output

There are total 5 items in your bucket
Marker
Note Book
Paper Clip
Paper Weight
Pen

2. Forget to mention the return statement in a function

A function also returns a None value if the interpreter does not encounter any return statement inside the function.


Error Example

Let’s say we are creating a function that accepts a string value and remove all the vowels from the string.

# function to remove vowels
def remove_vowels(string):
	new_string = ""
	for ch in string:
		if ch not in "aeiou":
			new_string += ch

string = "Hello Geeks Welcome to TechGeekBuzz"

new_string = remove_vowels(string)   #None

string_len = len(string)

new_string_len = len(new_string)   #error

print("The Length of actual string is:", string_len)

print("The Length of new string after vowels removal is:", new_string_len)


Output

Traceback (most recent call last):
  File "main.py", line 14, in 
    new_string_len = len(new_string)   #error
TypeError: object of type 'NoneType' has no len()

In this example, we are getting the error in line 14 with the

new_string_len = len(new_string)

statement. In line 14, we are trying to get the length of the

new_string

value that we have computed with the function

remove_vowels()

. We are getting this error because in line 14, the value of

new_string

is

None

.


Solution

To debug the above example, we need to ensure that we are returning a value from the

remove_vowels()

function, using the return statement.

# function to remove vowels
def remove_vowels(string):
	new_string = ""
	for ch in string:
		if ch not in "aeiou":
			new_string += ch
	
	return new_string

string = "Hello Geeks Welcome to TechGeekBuzz"

new_string = remove_vowels(string)   

string_len = len(string)

new_string_len = len(new_string)   

print("The Length of the actual string is:", string_len)

print("The Length of the new string after vowels removal is:", new_string_len)


Output

The Length of the actual string is: 35
The Length of the new string after vowels removal is: 23

Conclusion

The Python

len()

function can only operate on iterable objects like a list, tuple, string, dictionary, and set. If we try to operate it on a

NoneType object

, there we encounter the error «TypeError: the object of type ‘NoneType’ has no len()».

To debug this error, we need to ensure that the object whose length we are trying to find using the len() function does not have a None value.

If you are still getting this error in your Python program, please share your code and query in the comment section. We will try to help you in debugging.


People are also reading:

  • Python NameError name is not defined Solution

  • How to automate login using selenium in python?

  • Python IndexError: tuple index out of range Solution

  • How to extract all stored chrome password with Python?

  • Python SyntaxError: positional argument follows keyword argument Solution

  • Install python package using jupyter Notebook

  • Python AttributeError: ‘NoneType’ object has no attribute ‘append’Solution

  • How to delete emails in Python?

  • Python typeerror: ‘list’ object is not callable Solution

  • How to use Gmail API in python to send mail?

The len() method only works on iterable objects such as strings, lists, and dictionaries. This is because iterable objects contain sequences of values. If you try to use the len() method on a None value, you’ll encounter the error “TypeError: object of type ‘NoneType’ has no len()”.

In this guide, we talk about what this error means and how it works. We walk through two examples of this error in action so you can figure out how to solve it in your code.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

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

NoneType refers to the None data type. You cannot use methods that would work on iterable objects, such as len(), on a None value. This is because None does not contain a collection of values. The length of None cannot be calculated because None has no child values.

This error is common in two cases:

  • Where you forget that built-in functions change a list in-place
  • Where you forget a return statement in a function

Let’s take a look at each of these causes in depth.

Cause #1: Built-In Functions Change Lists In-Place

We’re going to build a program that sorts a list of dictionaries containing information about students at a school. We’ll sort this list in ascending order of a student’s grade on their last test.

To start, define a list of dictionaries that contains information about students and their most recent test score:

students = [
	{"name": "Peter", "score": 76 },
	{"name": "Richard", "score": 63 },
{"name": "Erin", "score": 64 },
{"name": "Miley", "score": 89 }
]

Each dictionary contains two keys and values. One corresponds with the name of a student and the other corresponds with the score a student earned on their last test. Next, use the sort() method to sort our list of students:

def score_sort(s):
	return s["score"]



sorted_students = students.sort(key=score_sort)

We have declared a function called “score_sort” which returns the value of “score” in each dictionary. We then use this to order the items in our list of dictionaries using the sort() method.

Next, we print out the length of our list:

print("There are {} students in the list.".format(len(sorted_students)))

We print out the new list of dictionaries to the console using a for loop:

for s in sorted_students:
	print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

This code prints out a message informing us of how many marks a student earned on their last test for each student in the “sorted_students” list. Let’s run our code:

Traceback (most recent call last):
  File "main.py", line 13, in <module>
	print("There are {} students in the list.".format(len(sorted_students)))
TypeError: object of type 'NoneType' has no len()

Our code returns an error.

To solve this problem, we need to remove the code where we assign the result of the sort() method to “sorted_students”. This is because the sort() method changes a list in place. It does not create a new list.

Remove the declaration of the “sorted_students” list and use “students” in the rest of our program:

students.sort(key=score_sort)

print("There are {} students in the list.".format(len(students)))

for s in students:
	print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

Run our code and see what happens:

There are 4 students in the list.
Richard earned a score of 63 on their last test.
Erin earned a score of 64 on their last test.
Peter earned a score of 76 on their last test.
Miley earned a score of 89 on their last test.

Our code executes successfully. First, our code tells us how many students are in our list. Our code then prints out information about each student and how many marks they earned on their last test. This information is printed out in ascending order of a student’s grade.

Cause #2: Forgetting a Return Statement

We’re going to make our code more modular. To do this, we move our sorting method into its own function. We’ll also define a function that prints out information about what score each student earned on their test.

Start by defining our list of students and our sorting helper function. We’ll borrow this code from earlier in the tutorial.

students = [
	{"name": "Peter", "score": 76 },
	{"name": "Richard", "score": 63 },
{"name": "Erin", "score": 64 },
{"name": "Miley", "score": 89 }
]

def score_sort(s):
	return s["score"]

Next, write a function that sorts our list:

def sort_list(students):
	students.sort(key=score_sort)

Finally, we define a function that displays information about each students’ performance:

def show_students(new_students):
	print("There are {} students in the list.".format(len(students)))
	for s in new_students:
			 print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

Before we run our code, we have to call our functions:

new_students = sort_list(students)
show_students(new_students)

Our program will first sort our list using the sort_list() function. Then, our program will print out information about each student to the console. This is handled in the show_students() function.

Let’s run our code:

Traceback (most recent call last):
  File "main.py", line 21, in <module>
	show_students(new_students)
  File "main.py", line 15, in show_students
	print("There are {} students in the list.".format(len(new_students)))
TypeError: object of type 'NoneType' has no len()

Our code returns an error. This error has occured because we have forgotten to include a “return” statement in our “sort_list” function.

When we call our sort_list() function, we assign its response to the variable “new_students”. That variable is passed into our show_students() function that displays information about each student. To solve this error, we must add a return statement to the sort_list() function:

def sort_list(students):
	students.sort(key=score_sort)
	return students

Run our code:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

There are 4 students in the list.
Richard earned a score of 63 on their last test.
Erin earned a score of 64 on their last test.
Peter earned a score of 76 on their last test.
Miley earned a score of 89 on their last test.

Our code returns the response we expected.

Conclusion

The “TypeError: object of type ‘NoneType’ has no len()” error is caused when you try to use the len() method on an object whose value is None.

To solve this error, make sure that you are not assigning the responses of any built-in list methods, like sort(), to a variable. If this does not solve the error, make sure your program has all the “return” statements it needs to function successfully.

Now you’re ready to solve this problem like a Python professional!

None object in Python has a data type which is referred to as “NoneType”. The None value is not equal to “0” it is equal to None/Null because it has a specific memory size in Python. The len() function in Python is utilized to get the length of any input variable other than None. If None is passed inside the len() function, it will return a “TypeError ”. To resolve this error, various functions are used in  Python.

This write-up will provide various reasons and solutions for “TypeError: object of type NoneType has no len()” in Python. The following aspects will be discussed in this guide:

  • Reason 1: Assigning None Value to len() Function
  • Solution 1: Change the None Value
  • Solution 2: Using an if-else Statement
  • Reason 2: Function Returns None
  • Solution: Use return Statement
  • Reason 3: Function returns None if Condition Not Satisfied
  • Solution: Initialize Empty List Inside the Function
  • Reason 4: sort() Method Return None
  • Solution: Find Length of the Original List Instead of the Sort List

So, let’s get started!

Reason 1: Assigning None Value to len() Function

One of the prominent reasons that invokes the “object of type NoneType has no len()” error is when the “None” value is assigned to the len() function in Python. An example snippet that shows the stated error is given below:

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

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

NoneType refers to the None data type. You cannot use methods that would work on iterable objects, such as len(), on a None value. This is because None does not contain a collection of values. The length of None cannot be calculated because None has no child values.

This error is common in two cases:

  • Where you forget that built-in functions change a list in-place
  • Where you forget a return statement in a function

Let’s take a look at each of these causes in depth.

Cause #1: Built-In Functions Change Lists In-Place

We’re going to build a program that sorts a list of dictionaries containing information about students at a school. We’ll sort this list in ascending order of a student’s grade on their last test.

To start, define a list of dictionaries that contains information about students and their most recent test score:

students = [
	{"name": "Peter", "score": 76 },
	{"name": "Richard", "score": 63 },
{"name": "Erin", "score": 64 },
{"name": "Miley", "score": 89 }
]

Each dictionary contains two keys and values. One corresponds with the name of a student and the other corresponds with the score a student earned on their last test. Next, use the sort() method to sort our list of students:

def score_sort(s):
	return s["score"]



sorted_students = students.sort(key=score_sort)

We have declared a function called “score_sort” which returns the value of “score” in each dictionary. We then use this to order the items in our list of dictionaries using the sort() method.

Next, we print out the length of our list:

print("There are {} students in the list.".format(len(sorted_students)))

We print out the new list of dictionaries to the console using a for loop:

for s in sorted_students:
	print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

This code prints out a message informing us of how many marks a student earned on their last test for each student in the “sorted_students” list. Let’s run our code:

Traceback (most recent call last):
  File "main.py", line 13, in <module>
	print("There are {} students in the list.".format(len(sorted_students)))
TypeError: object of type 'NoneType' has no len()

Our code returns an error.

To solve this problem, we need to remove the code where we assign the result of the sort() method to “sorted_students”. This is because the sort() method changes a list in place. It does not create a new list.

Remove the declaration of the “sorted_students” list and use “students” in the rest of our program:

students.sort(key=score_sort)

print("There are {} students in the list.".format(len(students)))

for s in students:
	print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

Run our code and see what happens:

There are 4 students in the list.
Richard earned a score of 63 on their last test.
Erin earned a score of 64 on their last test.
Peter earned a score of 76 on their last test.
Miley earned a score of 89 on their last test.

Our code executes successfully. First, our code tells us how many students are in our list. Our code then prints out information about each student and how many marks they earned on their last test. This information is printed out in ascending order of a student’s grade.

Cause #2: Forgetting a Return Statement

We’re going to make our code more modular. To do this, we move our sorting method into its own function. We’ll also define a function that prints out information about what score each student earned on their test.

Start by defining our list of students and our sorting helper function. We’ll borrow this code from earlier in the tutorial.

students = [
	{"name": "Peter", "score": 76 },
	{"name": "Richard", "score": 63 },
{"name": "Erin", "score": 64 },
{"name": "Miley", "score": 89 }
]

def score_sort(s):
	return s["score"]

Next, write a function that sorts our list:

def sort_list(students):
	students.sort(key=score_sort)

Finally, we define a function that displays information about each students’ performance:

def show_students(new_students):
	print("There are {} students in the list.".format(len(students)))
	for s in new_students:
			 print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

Before we run our code, we have to call our functions:

new_students = sort_list(students)
show_students(new_students)

Our program will first sort our list using the sort_list() function. Then, our program will print out information about each student to the console. This is handled in the show_students() function.

Let’s run our code:

Traceback (most recent call last):
  File "main.py", line 21, in <module>
	show_students(new_students)
  File "main.py", line 15, in show_students
	print("There are {} students in the list.".format(len(new_students)))
TypeError: object of type 'NoneType' has no len()

Our code returns an error. This error has occured because we have forgotten to include a “return” statement in our “sort_list” function.

When we call our sort_list() function, we assign its response to the variable “new_students”. That variable is passed into our show_students() function that displays information about each student. To solve this error, we must add a return statement to the sort_list() function:

def sort_list(students):
	students.sort(key=score_sort)
	return students

Run our code:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

There are 4 students in the list.
Richard earned a score of 63 on their last test.
Erin earned a score of 64 on their last test.
Peter earned a score of 76 on their last test.
Miley earned a score of 89 on their last test.

Our code returns the response we expected.

Conclusion

The “TypeError: object of type ‘NoneType’ has no len()” error is caused when you try to use the len() method on an object whose value is None.

To solve this error, make sure that you are not assigning the responses of any built-in list methods, like sort(), to a variable. If this does not solve the error, make sure your program has all the “return” statements it needs to function successfully.

Now you’re ready to solve this problem like a Python professional!

None object in Python has a data type which is referred to as “NoneType”. The None value is not equal to “0” it is equal to None/Null because it has a specific memory size in Python. The len() function in Python is utilized to get the length of any input variable other than None. If None is passed inside the len() function, it will return a “TypeError ”. To resolve this error, various functions are used in  Python.

This write-up will provide various reasons and solutions for “TypeError: object of type NoneType has no len()” in Python. The following aspects will be discussed in this guide:

  • Reason 1: Assigning None Value to len() Function
  • Solution 1: Change the None Value
  • Solution 2: Using an if-else Statement
  • Reason 2: Function Returns None
  • Solution: Use return Statement
  • Reason 3: Function returns None if Condition Not Satisfied
  • Solution: Initialize Empty List Inside the Function
  • Reason 4: sort() Method Return None
  • Solution: Find Length of the Original List Instead of the Sort List

So, let’s get started!

Reason 1: Assigning None Value to len() Function

One of the prominent reasons that invokes the “object of type NoneType has no len()” error is when the “None” value is assigned to the len() function in Python. An example snippet that shows the stated error is given below:

The output shows a TypeError that occurs when the len() function tries to calculate the length of the none-type variable.

Solution 1: Change the None Value

To solve this error, locate the variable where the “None” type value is assigned and change it to some other value.

Code:

value = [1,2,3,4,5]

len_value = len(value)

print(len_value)

In the above code, a list is created instead of a none-type value. The list variable is passed to the “len()” function; consequently, it returns the length of the list.

Output:

The above output successfully calculates the length of the input variable.

Solution 2: Using an if-else Statement

Another way to resolve the specified error is by using an “if-else” statement in the program. The example code of this solution is shown below:

Code:

list_value = None

if list_value is not None:
    print(len(list_value))
else:
    print('None value Found in List')

In the above code, the “None” value is assigned to a variable named “list_value”. The “if” statement determines whether a variable has a value of “None”. if the variable has a “None” value, then the “if” condition becomes “False”, and the “else” block will execute.

Output: 

The above output shows that the given variable has a “None” value.

Reason 2: Function Returns None

The stated error occurs when the user-defined function returns the “NoneType” value. An example of this is shown below; let’s look:

The above-given error snippet shows that the function returns a “None” value, due to which the TypeError arises in the output.

Solution: Use return Statement

To rectify this error, we simply need to return some value to the function because when the function is accessed, the return value will be executed.

Code:

def examples():
    return([1, 22, 33])

list_val = examples()

print(len(list_val))

In the above code, the “return” statement is used to return the value to a function named “examples”. The “len()” function accepts the return value as an argument and determines the length.

Output:

The above output shows that the return statement calculated the length of the given list.

Reason 3: Function returns None if Condition Not Satisfied

This “TypeError” also appears at the output when the condition written inside the function is not fulfilled. For instance, look at the following snippet:

The above output shows the error because the condition inside the function is not satisfied.

Solution: Initialize an Empty List Inside the Function

One approach to resolve this error is by returning an empty list to the function. When the empty list is returned, the value will be “zero” at the output.

Code:

def examples(num):
    if len(num) > 3:
        return num
    return []

list_val = examples([5, 7, 8])

print(len(list_val))

In the above code, the user-defined function is defined and the “if” statement executes its block of code when the condition is satisfied. But when the condition is not satisfied, an empty list will be returned back to the function.

Output:

The output proves that when the specified condition becomes false, the function retrieves 0 instead of throwing a TypeError.

Reason 4: sort() Method Return None

Some of the built-in methods in Python return a None value, such as the “sort()” method. The “sort()” method will update the existing list and return None.

The above output successfully sorts the given list; however, it throws an error when the len() function accepts a variable that holds the sorted list.

Solution: Find the Length of the Original List Instead of the Sort list

To solve this error, we simply need to input the original list variable inside the “len()” function rather than the variable of the sorted list.

Code:

list_val = [44,12,56,76,88]

sort_value=list_val.sort()

print(list_val)

print(len(list_val))

In the above code, the len() function takes the original list variable named “list_val” as an argument instead of the sort list variable named “sort_value”.

Output:

The above output shows the sorted list and the length of the sorted list.

That’s it from this guide!

Conclusion

The “object of type NoneType has no len()” error occurs when the “None” value is passed inside the “len()” function in Python. To resolve this error, various solutions are used in Python, i.e., changing the “NoneType” value, using an if-else statement, using a return statement, etc. The best way to resolve this error is to locate the variable/function where the “None” type value is assigned and change it to another value. The “if-else” statement is also used to check whether the input variable has a “None” value. This Python article presented various reasons and respective solutions for the “object of type NoneType has no len()” error, along with appropriate examples.

Понравилась статья? Поделить с друзьями:
  • U0073 ошибка тойота камри 50
  • U0073 ошибка опель астра j
  • U0073 ошибка toyota land cruiser 200
  • U0073 ошибка toyota camry 50
  • U0073 00 ошибка chevrolet cruze