Python TypeError: can only concatenate tuple (not "int") to tuple

12.6k views Asked by At

I am providing two values (mon_voltage and core_voltage) through command line, and I need to search a 'start point' from a two dimensional array from where my iteration or loop will start.

Here is my code:

myArray =  [[1.02,1.13],[1.02,1.16],[1.02,1.18],[1.02,1.21],[1.02,1.265]]

start_point = myArray.index([mon_voltage, core_voltage])
print "Start point is", start_point

for idx in enumerate(myArray):

     mon_voltage = myArray[idx + start_point][0]
     core_voltage = myArray[idx + start_point][1]

I am getting the following error:

  TypeError: can only concatenate tuple (not "int") to tuple

I am unable to figure out why start_point, which is an index, is a tuple. Please help.

5

There are 5 answers

0
nu11p01n73R On BEST ANSWER

The enumerate() will return a (index, value) tuple.

You can access the index value as

idx[0]

Example

for idx in enumerate(myArray):    
       mon_voltage = myArray[idx[0] + start_point][0]
       core_voltage = myArray[idx[0] + start_point][1]

OR

for (idx, value) in enumerate(myArray):    
           mon_voltage = myArray[idx + start_point][0]
           core_voltage = myArray[idx + start_point][1]

Here the tuple is unpacked to idx and value and we use the idx for following logic what so ever may occur within the for loop.

The value will contain the value at index position idx that is myArray[idx]

0
Rick On

The tuple is idx, not start_point. This line:

for idx in enumerate(myArray):

Assigns a tuple object to idx. The enumerate function produces a tuple of the form:

(index_number, value)

What you probably want to do is just:

for idx, value in enumerate(myArray):

And ignore the value part.

0
Konstantin On

idx is a tuple, while start_point isn't

Builtin function enumerate returns an iterator whose next will return tuples containing a count and a value obtained from sequence

In your case following tuples are returned

In [5]: list(enumerate(myArray))
Out[5]:
[(0, [1.02, 1.13]),
 (1, [1.02, 1.16]),
 (2, [1.02, 1.18]),
 (3, [1.02, 1.21]),
 (4, [1.02, 1.265])]
0
yvespeirsman On

Start_point is not a tuple; idx is. If you print(idx), you'll see the output of the enumerate() method:

(0, [1.02, 1.13])
(1, [1.02, 1.16])
(2, [1.02, 1.18])
(3, [1.02, 1.21])
(4, [1.02, 1.265]) 

These are all tuples, consisting of an index and value.

0
alec_djinn On

idx is indeed a tuple since enumerate() return a tuple. If you want to extract the real index then try idx[0].