Python 'TypeError': 'Generator' object is not subscriptable

Ropstah picture Ropstah · Sep 7, 2014 · Viewed 11k times · Source

I'm trying to perform a simple Euclid example in Python but receive the error mentioned in the title. The code is as follows:

def gcd1(a,b):
        """ the euclidean algorithm """
        while a:
                a, b = b%a, a
        return b

I'm calling the code as follows (i think this might have something to do with it):

for x in set1:
    print(gcd1(x, set2[x]))

Edit: current situation (works)


set1 = list(range(start, end))
""" otherrange() behaves just like range() however returns a fixed list"""
set2 = list(otherrange(start, end))

for x in set1:
    print(gcd1(x, set2[x]))

Answer

randomusername picture randomusername · Sep 7, 2014

This means that set2 is a generator, to get around this just turn it into a list.

set2_list = list(set2)
for x in set1:
    print(gcd1(x, set2_list[x]))