Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Luke Thornton
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.
Here is an example of how the error occurs.
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
.
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.
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.
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.
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.
my_list = ['apple', 'banana', 'kiwi'] result = len(my_list) print(result) # 👉️ 3
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.
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.