Skip to content

Comment on Python bug: Can assign [] = (), but not () = []

Comments

>> [a, b] = 2, 3
>> (a, b) = 2, 3
>> {a, b} = 2, 3
  File "<interactive input>", line 1
SyntaxError: can't assign to literal

That could be because sets aren't ordered (even though it looks odd in this context).

I thought that at first too, but even then the exception seems spurious. It would be more inline with existing Python behavior to evaluate it as undefined/indeterminate assignment order (though this would be pretty useless).

>> a, b, c, d = {1, 2, 3, 'a'}
>> a

'a'

Regardless, it shouldn't be surprising when writing insane code, that the language starts acting insane. Python as a whole is pretty decent when it comes to handling syntactic edge cases.

The tricky part is that the [a,b] and (a,b) in your original examples are not list/tuple literals, but a target_list according to Python's grammar [0], which can be optionally enclosed in parentheses or brackets. To be honest, I didn't know the latter were allowed, even though I've been using Python for years. IMHO, they should have just allowed parentheses. It's like the parentheses in function calls--not really a tuple, but syntactic grouping. Why have more that one way to do the same thing?

[0]: https://docs.python.org/3/reference/simple_stmts.html#assign...

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.