5

I have found something like this in a code I'm working with:

[], my_variable = my_function(a, b)

where the output of my_function goes like:

return some_dict, some_list

This seems to work - unit tests of a system don't fail, but when I try this at the python console (assigning dictionary to "[]") it raises:

ValueError: too many values to unpack

Have you seen something like this? How does assigning a dictionary (or something else) to empty list constant "[]" work?

Or it doesn't and tests are missing something...

Gwidryj
  • 915
  • 1
  • 7
  • 12
  • Actual `my_function` code would be helpful - likely the first result is not a dict at all: `[], qwe = {1:1}, '12'` throws value error – J0HN Sep 09 '15 at 12:33
  • 1
    `[], a = ({}, 1)` works, though. – Kevin Sep 09 '15 at 12:34
  • `[a], qwe = {1:2}, '12'` works as well; `a` became 1 – J0HN Sep 09 '15 at 12:37
  • 5
    http://stackoverflow.com/questions/30147165/why-does-assigning-to-an-empty-list-e-g-raise-no-error http://stackoverflow.com/questions/29870019/why-is-it-valid-to-assign-to-an-empty-list-but-not-to-an-empty-tuple – Padraic Cunningham Sep 09 '15 at 12:39

2 Answers2

2

It's because in your test file, the return value is {}.

>>> [] = {}
>>> [] = {1:2}
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: too many values to unpack


>>> [] = []
>>> [] = [1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
luoluo
  • 5,353
  • 3
  • 30
  • 41
1

You can't really assign to list, because it is not variable, you can use list syntax to assign to multiple variables:

[a, b, c] = [1, 2, 3]

Will just assign 1 to a and so forth.

What you are doing can be expressed with this expression:

[] = {"a":1}

What python tries to do is to match amount of items in dictionary with amount of items in the list. It finds mismatch and raises an error. You could do like that:

[x] = {"a":1}
Andrey
  • 59,039
  • 12
  • 119
  • 163