Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"'generator' object is not subscriptable" error

Why am I getting this error, from line 5 of my code, when attempting to solve Project Euler Problem 11?

for x in matrix:     p = 0     for y in x:         if p < 17:             currentProduct = int(y) * int(x[p + 1]) * int(x[p + 2]) * int(x[p + 3])             if currentProduct > highestProduct:                 print(currentProduct)                 highestProduct = currentProduct         else:                 break             p += 1 
'generator' object is not subscriptable 
like image 629
Matthew Hannah Avatar asked Jun 09 '11 04:06

Matthew Hannah


People also ask

How do you fix an object is not Subscriptable error?

The TypeError: 'int' object is not subscriptable error occurs if we try to index or slice the integer as if it is a subscriptable object like list, dict, or string objects. The issue can be resolved by removing any indexing or slicing to access the values of the integer object.

Are generators Subscriptable?

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] .

What is a generator object in Python?

Python generators are a simple way of creating iterators. All the work we mentioned above are automatically handled by generators in Python. Simply speaking, a generator is a function that returns an object (iterator) which we can iterate over (one value at a time).

What is Subscriptable object?

Some objects in Python are subscriptable. This means that they contain, or can contain, other objects. Integers are not a subscriptable object. They are used to store whole numbers. If you treat an integer like a subscriptable object, an error will be raised.


1 Answers

Your x value is is a generator object, which is an Iterator: it generates values in order, as they are requested by a for loop or by calling next(x).

You are trying to access it as though it were a list or other Sequence type, which let you access arbitrary elements by index as x[p + 1].

If you want to look up values from your generator's output by index, you may want to convert it to a list:

x = list(x) 

This solves your problem, and is suitable in most cases. However, this requires generating and saving all of the values at once, so it can fail if you're dealing with an extremely long or infinite list of values, or the values are extremely large.

If you just needed a single value from the generator, you could instead use itertools.islice(x, p) to discard the first p values, then next(...) to take the one you need. This eliminate the need to hold multiple items in memory or compute values beyond the one you're looking for.

import itertools  result = next(itertools.islice(x, p)) 
like image 172
Jeremy Avatar answered Oct 09 '22 04:10

Jeremy