Are you getting the error “generator object is not subscriptable“? Yes, you have come to the right place. Today in this tutorial, I will show you how to solve this error.
The error “TypeError: ‘generator’ object is not subscriptable in Python” occurs when we try to access the generator object at a specific index.
[Fixed] TypeError: ‘generator’ object is not subscriptable in Python
There are several methods to solve this error. We will discuss them all one by one. You can apply one according to your requirements.
Here is the Python code for how this error occurs:
def gen():
yield 5
yield 18
yield 23
gen_obj = gen()
# TypeError: 'generator' object is not subscriptable
print(gen_obj[0])
In the above code, we are trying to get the generator object at index[0] and we are getting the error.
Now let’s go to the solutions to this error.
[Fixed]: json.decoder.JSONDecodeError: Extra data
[Solution] Converting ‘generator’ object to ‘List’:
We can solve this error by just converting the generator object to the list and then can access the element of the list by index.
def gen():
yield 5
yield 18
yield 23
gen_obj = gen()
#Converting "Generator" to "List"
gen_list = list(gen_obj)
print(gen_list[1]) #OUTPUT: 18
[Fixed] Iterate over a generator using the ‘for’ loop.
You can use the ‘for‘ loop to iterate over the generator object to solve this error.
def gen():
yield 5
yield 18
yield 23
gen_obj = gen()
for i in gen_obj:
print(i)
#OUTPUT: 5,18,23
[Fix] Using the ‘next()’ function to iterate to the next item.
You can use the next() function to get rid of this error “TypeError: ‘generator’ object is not subscriptable in Python“.
def gen():
yield 5
yield 18
yield 23
gen_obj = gen()
print(next(gen_obj)) #OUTPUT: 1
print(next(gen_obj)) #OUTPUT: 2
print(next(gen_obj)) #OUTPUT: 3
Conclusion on TypeError: ‘generator’ object is not subscriptable in Python
Programmers, we discussed how we can solve the error “TypeError: ‘generator’ object is not subscriptable in Python“. If you are still getting the error please let us know in the comments section. You can solve this error “‘generator’ object is not subscriptable” using the above solutions.