ValueError vs IndexError, unpacking arguments with string.split

Dan Sommers 2QdxY4RzWzUUiLuE at potatochowder.com
Fri Nov 30 09:53:10 EST 2018


On 11/30/18 7:35 AM, Morten W. Petersen wrote:

> ... but isn't it logical that the
> string is parsed and split, and then later the unpacking operation fails
> with an IndexError?

With slightly simpler code and the full text of the exception,
the details becomes more apparent:

 >>> x, y = [4]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 2, got 1)

Python validates that the right hand side contains exactly the
right number of elements before beginning to unpack, presumably
to ensure a successful operation before failing part way through.

Effectively, Python is saying that you can't unpack a one-element
array into two pieces *before* it gets to the indexing logic.

HTH,
Dan



More information about the Python-list mailing list