Search code examples
pythonpython-itertools

TypeError: 'itertools.combinations' object is not subscriptable


When I try to run:

temp = (twoset2[x][i][0]-twoset[x][i][1])

I get:

TypeError: 'itertools.combinations' object is not subscriptable

My code:

for x in range(0,64):
    for i in range(0,1):
        temp = (twoset2[x][i][0]-twoset[x][i][1])
        DSET[counter2]= temp
        temp = 0
        counter2 += 1

Basically what I am trying to do is: I have a list (twoset2) of 2 element subsets of coordinates (so an example: ((2,0) (3,3)). I want to access each individual coordinate, and then take the difference between x and y and place it into DSET, but I get the above error when trying to run.

Please help!


Solution

  • itertools.combinations returns a generator and not a list. What this means is that you can iterate over it but not access it element by element with an index as you are attempting to.

    Instead you can get each combination like so:

    import itertools
    for combination in itertools.combinations([1,2,3], 2):
        print combination
    

    This gives:

    (1, 2)
    (1, 3)
    (2, 3)