Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 886
user168530 Avatar asked Jan 28 '15 18:01

user168530


People also ask

How do I install Itertools in Python 3?

itertools is a built-in module in python and does not need to be installed separately.

How does Itertools combinations work?

The itertools. combinations() function takes two arguments—an iterable inputs and a positive integer n —and produces an iterator over tuples of all combinations of n elements in inputs .

Why Itertool is used in Python?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.


1 Answers

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)
like image 61
Simon Gibbons Avatar answered Nov 04 '22 19:11

Simon Gibbons