newbieCoder
newbieCoder

Reputation: 23

Python -- too many values to unpack

I have this code

N, D = x.shape
running_mean = bn_param.get('running_mean', np.zeros(D, dtype=x.dtype))
running_var = bn_param.get('running_var', np.zeros(D, dtype=x.dtype))

and it's said: ValueError: too many values to unpack

I know that x has 50x3x32x32 dimension And I want to put the 50 in N variable and I need to put 3x32x32 in D variable. How could I do that? Thank you.

Upvotes: 2

Views: 92

Answers (1)

falsetru
falsetru

Reputation: 369394

x.shape has more than 2 values, not matching with the number of variables to unpack (multiple assignment):

>>> shape = (50, 3, 32, 32)
>>> N, D = shape
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

You can use index, slice operators to get what you want:

>>> shape = (50, 3, 32, 32)
>>> N, D = shape[0], shape[1:]  # [0] to get 1st, [1:] to get 2nd, 3rd,.. up to end
>>> N
50
>>> D
(3, 32, 32)

If you're using Python 3.x, you can use Extended iterable unpacking syntax:

>>> N, *D = shape
>>> N
50
>>> D
[3, 32, 32]

Upvotes: 4

Related Questions