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
294k52 gold badges301 silver badges346 bronze badges
asked May 19, 2015 at 8:48
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
MureinikMureinik
294k52 gold badges301 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
glglglglglgl
88.5k13 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 SableVivek Sable
9,8103 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.
-
TypeError
-
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.
- Reassign the list with None returning methods.
- 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 TypeError: object of type ‘NoneType’ has no len() error occurs while attempting to find the length of an object that returns ‘None’. The python object whose data type is NoneType can’t be used in length function. The Length function is used for data structures that store multiple objects.
The python variables, which have no value initialised, have no data type. These variables are not assigned any value, or objects. The length function can not be called the variables which are not allocated with any value or object. If you call the length function for these variables of none type, it will throw the error TypeError: object of type ‘NoneType’ has no len()
Exception
The error TypeError: object of type ‘NoneType’ has no len() will display the stack trace as below
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print (len(s))
TypeError: object of type 'NoneType' has no len()
[Finished in 0.1s with exit code 1]
How to reproduce this error
If a python variable is not assigned with any value, or objects, the variable would have none data type. If the length function is invoked for the none type variable, the error TypeError: object of type ‘NoneType’ has no len() will be thrown.
test.py
s=None
print (len(s))
Output
Traceback (most recent call last):
File "/Users/python/Desktop/test.py", line 2, in <module>
print (len(s))
TypeError: object of type 'NoneType' has no len()
[Finished in 0.1s with exit code 1]
Solution 1
The python variable which is not assigned with any value or object, should be assigned with a value or object. If the variable is not assigned with any value or object , assign with an object such as list, tuple, set, dictionary etc.
s=[1,2]
print (len(s))
Output
2
[Finished in 0.0s]
Solution 2
Due to the dynamic creation of the variable the python variable may not be assigned with values. The datatype of the variable is unknown. In this case, the None data type must be checked before the length function is called.
s=None
print type(s)
if s is None :
print "Value is None"
else:
print (len(s))
Output
Value is None
Solution 3
The python variable should be validated for the expected data type. If the variable has the expected data type, then the length function should be invoked. Otherwise, the alternate flow will be invoked.
s=None
print type(s)
if type(s) in (list,tuple,dict, str):
print (len(s))
else:
print "not a list"
Output
not a list
Solution 4
If the data type of the variable is unknown, the length function will be invoked with try and except block. The try block will execute if the python variable contains value or object. Otherwise, the except block will handle the error.
s=None
try :
print (len(s))
except :
print "Not a list"
Output
Not a list
[Finished in 0.0s]
When working with Python, you will likely encounter the error “TypeError: object of type ‘NoneType’ has no len()”. Let’s learn about the cause of this error as well as its solution through this article. Keep reading for detailed information.
What causes this error?
You will get the error message: “TypeError: object of type ‘NoneType’ has no len()” in Python when you try to pass in the len() function a value ‘None’.
The len() function in Python takes a single parameter – a collection or a sequence – and returns the length of that object.
Syntax:
len(object)
Where: object – Required parameter. An object. It must be a collection or a sequence.
Therefore, if you pass in the len() function a value of ‘None’, the error is obvious.
Here is an example of how this error occurs:
def getMessage(): print("Welcome to the LearnShareIT community.") # None value message = getMessage() print(len(message))
Error:
TypeError: object of type 'NoneType' has no len()
Since the getMessage() function does not return any value, the ‘message’ variable gets a value of ‘None’.
To work around this problem, ensure that the value you pass to len() is different from ‘None’.
As in the above example, we can use the return statement to get a value from the function.
def getMessage(): return "Welcome to the LearnShareIT community." message = getMessage() print(len(message))
Output:
38
Alternatively, you can also use the conditional statement to check if a variable is storing a ‘None’ value before passing it into the len() function.
message = None # Use the if/else block if message != None: print(len(message)) else: print("The variable is storing a 'None' value")
Output:
The variable is storing a 'None' value
At this point, you no longer have to worry about the error because the conditional statement prevents getting the length of a variable that stores a ‘None’ value.
Or you can also directly print the variable to be checked to see its value with the print() statement.
noneMessage = None message = "Welcome to the LearnShareIT community." print(noneMessage) print(message)
Output:
None
Welcome to the LearnShareIT community.
Summary
In summary, we have just shared with you the necessary information about the “TypeError: object of type ‘NoneType’ has no len()” in Python. To overcome this error, you need to check the value of the variable passed in the len() function and make sure it is different from a ‘None’ value. That’s the end of this post. Hopefully, the information we conveyed will be helpful to you.
My name’s Christopher Gonzalez. I graduated from HUST two years ago, and my major is IT. So I’m here to assist you in learning programming languages. If you have any questions about Python, JavaScript, TypeScript, Node.js, React.js, let’s contact me. I will back you up.
Name of the university: HUST
Major: IT
Programming Languages: Python, JavaScript, TypeScript, Node.js, React.js