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

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Luke Thornton

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

The Python "TypeError: object of type 'generator' has no len()" occurs when we pass a generator object to the len() function. To solve the error, convert the generator to a list before passing it to the len() function.

typeerror object of type generator has no len

Here is an example of how the error occurs.

main.py
def g(): yield 1 yield 2 yield 3 gen = g() print(type(gen)) # 👉️ <class 'generator'> # ⛔️ TypeError: object of type 'generator' has no len() print(len(gen))

We passed a generator object to the len() function which caused the error.

One way to solve the error is to convert the generator object to a list.

main.py
def g(): yield 1 yield 2 yield 3 # 👇️ convert to list my_list = list(g()) print(my_list) # 👉️ [1, 2, 3] print(len(my_list)) # 👉️ 3

We passed the generator object to the list() class to convert it to a list.

Note that once the generator is converted to a list, it is exhausted.

main.py
def g(): yield 1 yield 2 yield 3 # 👇️ convert to list gen = g() print(list(gen)) # 👉️ [1, 2, 3] print(list(gen)) # 👉️ []

This is why you have to convert the generator to a list and store the result in a variable.

You can iterate over a generator with a simple for loop.

main.py
def g(): yield 1 yield 2 yield 3 gen = g() for i in gen: print(i) # 👉️ 1, 2, 3

Alternatively, you can pass the generator to the next() function to retrieve the next item.

main.py
def g(): yield 1 yield 2 yield 3 gen = g() print(next(gen)) # 👉️ 1 print(next(gen)) # 👉️ 2 print(next(gen)) # 👉️ 3

The len() function returns the length (the number of items) of an object.

main.py
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # 👉️ 3
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

Notice that the len() function cannot be called with a generator.

If you didn't expect the variable to store a generator object, you have to correct the assignment.

If you aren't sure what type a variable stores, use the built-in type() class.

main.py
import types def g(): yield 1 yield 2 yield 3 # 👇️ convert to list gen = g() print(type(gen)) # 👉️ <class 'generator'> # 👇️ True print(isinstance(gen, types.GeneratorType))

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Use the search field on my Home Page to filter through my more than 1,000 articles.