Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError: too many values to unpack - Is it possible to ignore one value?

Tags:

python

The following line returns an error:

self.m, self.userCodeToUserNameList, self.itemsList, self.userToKeyHash, self.fileToKeyHash = readUserFileMatrixFromFile(x,True)

The function actually returns 6 values. But in this case, the last one is useless (its None). So i want to store only 5.

Is it possible to ignore the last value?

like image 418
Guy s Avatar asked Jul 28 '16 12:07

Guy s


People also ask

How do I stop too many values to unpack?

The “valueerror: too many values to unpack (expected 2)” error occurs when you do not unpack all the items in a list. This error is often caused by trying to iterate over the items in a dictionary. To solve this problem, use the items() method to iterate over a dictionary.

How do I fix too many values to unpack in Python?

We get this error when there's a mismatch between the number of variables to the amount of values Python receives from a function, list, or other collection. The most straightforward way of avoiding this error is to consider how many values you need to unpack and then have the correct number of available variables.

What is too many values to unpack expected 2?

ValueError: too many values to unpack (expected 2) occurs when there is a mismatch between the returned values and the number of variables declared to store these values. If you have more objects to assign and fewer variables to hold, you get a value error.

How do I fix ValueError is not enough values to unpack in Python?

The “ValueError: not enough values to unpack” error is raised when you try to unpack more values from an iterable object than those that exist. To fix this error, make sure the number of values you unpack from an iterable is equal to the number of values in that iterable.


2 Answers

You can use *rest from Python 3.

>>> x, y, z, *rest = 1, 2, 3, 4, 5, 6, 7
>>> x
1
>>> y
2
>>> rest
[4, 5, 6, 7]

This way you can always be sure to not encounter unpacking issues.

like image 194
Idos Avatar answered Oct 08 '22 02:10

Idos


It's common to use _ to denote unneeded variables.

a, b, c, d, e, _ = my_func_that_gives_6_values()

This is also often used when iterating a certain number of times.

[random.random() for _ in range(10)]  # gives 10 random values

Python 3 also introduced the * for assignment, similar to how *args takes an arbitrary number of parameters. To ignore an arbitrary number of arguments, just assign them to *_:

a, b, c, d, e, *_ = my_func_that_gives_5_or_more_values()

This can be used at any point in your assignment; you can fetch the first and last values and ignore padding in the middle:

>>> a, b, c, *_, x, y, z = range(10)
>>> print(a, b, c, '...', x, y, z)
0 1 2 ... 7 8 9
like image 22
MisterMiyagi Avatar answered Oct 08 '22 03:10

MisterMiyagi