Home > OS >  Explanation for ValueError: too many values to unpack (expected 2)
Explanation for ValueError: too many values to unpack (expected 2)

Time:11-10

I understand in the code below that I am supposed to use [i,j,k] (or a single variable) to retrieve my return values. However, I have assigned two (only i and j), instead of three to the function. This gives the error "ValueError: too many values to unpack (expected 2)". I am still trying to understand the error. Is the error not supposed to be "ValueError: not enough values to unpack (expected 3)" or perhaps because python indexes from 0, (expected 2)?

def fn(x,y):
    a = x*5
    b = a*y
    h = b - 3
    return a,b,h
[i, j] = fn5(5,2)

CodePudding user response:

No its not due to indexing from 0.

What happens under the hood is that first your function fn is evaluated, which then returns 3 values, a, b, h. Then the interpreter tries to assign these 3 values into your two variables i, j (essentially unpacking them). Since the left hand side contains 2 variables, the interpreter expects that the right hand size contains 2 values. As the right hand side in fact contains 3 variables, you get the error "ValueError: Too many values to unpack (expected 2)"

CodePudding user response:

It is because your function returns 3 elements, but you trying to set it to 2 variables. So python doesn't know what to do and raises error

def fn(x,y):
    a = x*5
    b = a*y
    h = b - 3
    return a,b,h
i, j, k = fn(5,2)

If you rewrite your code so result of function will be set to 3 variables, code will run without errors

  • Related