What surprised me about the Python assignment puzzle
Yesterday I wrote about a Python assignment puzzle and how it worked, but I forgot to write about what was surprising about it for me. The original puzzle is:
(a, b) = a[b] = {}, 5
The head-scratching bit for me was the middle, including the whole question of 'how does this even work'. So the real surprise here for me is that in serial assignments, Python processes the assignments left to right.
The reason this was a big surprise is due to what was my broad
mental model of serial assignment, which comes from C. In C,
assignment is an expression that yields the value assigned (ie the
value of 'a = 2
' is 2
). So in C and languages like this, serial
assignment is a series of assignment expressions that happen right
to left; you start out with the actual expression producing a value,
you do the rightmost assignment which yields the value again, and
you ripple leftwards. So a serial assignment groups like this:
a = (b = (c = (d = <expression>)))
Python doesn't work this way, of course; assignment is not an expression and doesn't produce a value. But I was still thinking of serial assignment as proceeding right to left by natural default and was surprised to learn that Python has chosen to do it in the other order. There's nothing wrong with this and it's perfectly sensible; it's just a decision that was exactly opposite from what I had in my mind.
(Looking back, I assumed in this entry that Python's serial assignment order was right to left without bothering to look it up.)
How did my misapprehension linger for so long? Well, partly it's that I don't use serial assignment very much in Python; in fact, I don't think anyone does much of it and I have the vague impression that it's not considered good style. But it's also that it's quite rare for the assignment order to actually matter, so you may not discover a mistaken belief about it for a very long time. This puzzle is a deliberately perverse exercise where it very much does matter, as the leftmost assignment actively sets up the variables that the next assignment then uses.
Comments on this page:
|
|