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.

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

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.

Buy Me a Coffee