TypeError: 'generator' object is not subscriptable in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'generator' object is not subscriptable in Python #

The Python "TypeError: 'generator' object is not subscriptable" occurs when we try to access a generator object at a specific index. To solve the error, pass the generator to the list constructor, e.g. list(gen)[0].

typeerror generator object is not subscriptable

Here is an example of how the error occurs

main.py
def g(): yield 1 yield 2 yield 3 gen = g() print(type(gen)) # ⛔️ TypeError: 'generator' object is not subscriptable print(gen[0])

We used square brackets to try to access the element at index 0, but the generator object is not subscriptable.

We can get around this by converting the generator object to a list.

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

List objects are subscriptable, so we can access the element at a specific index after converting the generator object to a list.

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

Note that if you try to access a list index that is out of bounds, you would get an error. You can use a try/except statement if you need to handle that.

main.py
def g(): yield 1 yield 2 yield 3 my_list = list(g()) try: print(my_list[100]) except IndexError: print('index out of bounds') # 👉️ this runs

The example catches the IndexError that is thrown if the index is out of bounds.

The list constructor takes an iterable, such as a generator object, and converts it to a list.

The list constructor builds a list whose items are the same and in the same order as the iterable's items.

The list constructor takes an iterable that may be a sequence, a container that supports iteration or an iterator object.

Conclusion #

The Python "TypeError: 'generator' object is not subscriptable" occurs when we try to access a generator object at a specific index. To solve the error, pass the generator to the list constructor, e.g. list(gen)[0].

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.