How to Solve Python TypeError: object of type ‘generator’ has no len()

by | Programming, Python, Tips

This error occurs when you pass a generator object to a len() method call. The generator object is a type of lazy iterator containing a sequence of values. In Python, iterators do not have length.

We can solve the error by converting the generator object to a list object using the built-in list() method.

For example,

# A generator function
def generator_func():
    yield 1
    yield 2
    yield 3
   
# x is a generator object
x = list(generator_func())

print(len(x))

This tutorial will go through how to solve the error with code examples.


TypeError: object of type ‘generator’ 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 generator.

The part ‘has no len()‘ tells us the map object does not have a length, and therefore len() is an illegal operation for the generator object.

Retrieving the length of an object is only suitable for iterable objects, like a list or a tuple.

A generator function returns a generator object, an iterator containing a sequence of values. We can access the values in a generator object using a for loop or by calling next().

All iterators have the __iter__ dunder method, which we can check by passing the iterator to the dir() method:

# A generator function
def generator_func():
    yield 1
    yield 2
    yield 3
   
# x is a generator object
x = generator_func()

print(type(x))
print('__iter__' in dir(x))
<class 'generator'>
True

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 the generator object and the list object using the built-in dir() method.

# A generator function
def generator_func():
    yield 1
    yield 2
    yield 3
   
# x is a generator object
x = generator_func()

print(type(x))
print('__len__' in dir(x))
<class 'generator'>
False

We can see that __len__ is not present in the attributes of the generator object.

lst = ["Einstein", "Feynman", "Dirac"]

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

Let’s look at an example of trying to get the length of a generator object. First, we will create the generator() function.

Generator functions allow us to declare a function that behaves like an iterator. We use a yield statement rather than a return statement in a generator function.

def generator_func():

    yield 2

    yield 3

    yield 8

Next, we will assign the generator object returned by the generator function to a variable,

x = generator_func()

Next, we will try to get the length of the generator object and print it to the console.

print(len(x))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 print(len(x))

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

The error occurs because the generator object is an iterator and does not have a length.

Solution

We can solve the error by converting the generator object to a list, which is an iterable data type. We can convert a generator object to a list using the built-in list() method. Let’s look at the revised code:

def generator_func():

    yield 2

    yield 3

    yield 8

x = list(generator_func())

print(type(x))
print(len(x))

Let’s run the code to get the length of the list:

<class 'list'>
3

We successfully converted the generator object to a list and then used the len() method to get the length of the list.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on the has no len() TypeErrors, go to the article:

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.

Research Scientist at Moogsoft | + posts

Suf is a research scientist at Moogsoft, specializing in Natural Language Processing and Complex Networks. Previously he was a Postdoctoral Research Fellow in Data Science working on adaptations of cutting-edge physics analysis techniques to data-intensive problems in industry. In another life, he was an experimental particle physicist working on the ATLAS Experiment of the Large Hadron Collider. His passion is to share his experience as an academic moving into industry while continuing to pursue research. Find out more about the creator of the Research Scientist Pod here and sign up to the mailing list here!