0

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.

1
  • Thanks to everyone for your valuable inputs !! Commented Jun 9, 2015 at 13:58

5 Answers 5

6

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]

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.