Thom Yorke - 2 years ago 173
Python Question

# Itertools product ValueError: too many values to unpack (expected 2)

I know this question gets repeated a lot but I haven't seen one that deals with this specific problem. I got this function that takes the length of a numpy array, and then takes the cross product:

``````def solve(tab, vacios):
if vacios == 0:
return is_valid( tab ) #Not important here
large = len(tab)
for fila, col in product(range(large), repeat=(large-1)):
``````

But I get this error:

``````ValueError: too many values to unpack (expected 2)
``````

I don't really know what to do, so if you could help me it'd be great, thanks!

You are producing a combination of `large-1` values every iteration, because that's what you set the `repeat` argument to:

``````product(range(large), repeat=(large-1):
``````

but are unpacking values into two variables, `fila` and `col`:

``````for fila, col in product(range(large), repeat=(large-1)):
``````

If you pass in a `tab` value with a length other than 3, that'll always be the wrong number of values to unpack.

For example, if `len(tab)` is 4, you produce tuples of length 3:

``````>>> from itertools import product
>>> large = 4
>>> list(product(range(large), repeat=large - 1))
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (0, 3, 0), (0, 3, 1), (0, 3, 2), (0, 3, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3), (1, 3, 0), (1, 3, 1), (1, 3, 2), (1, 3, 3), (2, 0, 0), (2, 0, 1), (2, 0, 2), (2, 0, 3), (2, 1, 0), (2, 1, 1), (2, 1, 2), (2, 1, 3), (2, 2, 0), (2, 2, 1), (2, 2, 2), (2, 2, 3), (2, 3, 0), (2, 3, 1), (2, 3, 2), (2, 3, 3), (3, 0, 0), (3, 0, 1), (3, 0, 2), (3, 0, 3), (3, 1, 0), (3, 1, 1), (3, 1, 2), (3, 1, 3), (3, 2, 0), (3, 2, 1), (3, 2, 2), (3, 2, 3), (3, 3, 0), (3, 3, 1), (3, 3, 2), (3, 3, 3)]
``````

Either hardcode `repeat` to `2` or don't try to unpack a variable number of values into a fixed number of variables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download