1

I have a tuple of arrays like the following:

z = (array( [ [1], [2], [3]] ),
     array( [[10],[11],[12]] )
    )

I want to iterate over them with a simple for loop using two variables:

for x, y in z:
    print("it worked")
    self.doStuff(x, y)

... but it throws the error:

ValueError: too many values to unpack (expected 2)

I have googled this error. Many seem to suggest the .split() method or .items(). I'm not really sure, where to add those, since the don't belong to tuples. How can I execute this for-loop properly? Thanks for your help.

1
  • I assume you are trying to iterate over the arrays' elements, not over the tuple's elements, right? If so, you should re-think your data structures -- an iteration over a single 2-tuple unpacking 2 values results in a single run, where you unpack the 2 complete arrays from the tuple. Commented Sep 28, 2016 at 12:44

2 Answers 2

2

Reading the other answer it might be that I misunderstood what you want.

You can also use

for x,y in zip(*z):

to unzip the z tuple.

The output then is:

it worked
[1] [10]
it worked
[2] [11]
it worked
[3] [12]
Sign up to request clarification or add additional context in comments.

Comments

2

The line

for x, y in z:

assumes (at least in Python2.7), that each element in z can be tuple unpacked. This would be the case if each element in z is, say, a pair tuple:

In [23]: for x, y in [(1, 2), (3, 4)]:
    ...:     pass
    ...: 

For your case, could it be that you simply want

x, y = z

?

This works by me:

In [19]: z = (array( [ [1], [2], [3]] ),
    ...:      array( [[10],[11],[12]] )
    ...:     )

In [20]: x, y = z

In [21]: x
Out[21]: 
array([[1],
       [2],
       [3]])

In [22]: y
Out[22]: 
array([[10],
       [11],
       [12]])

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.