I believe I answered my own question while trying to figure out how to ask it properly, but since I found the answer in Python's documentation to be rather opaque, I thought I'd still post the question here.
While trying to understand the rules of single-line assignments in Python, I came across some examples that contradict the usual statement that "single-line assignments to multiple variables all take place at once".
a = 0 # variable 'a' must be assigned first
a, b = 1, a # a, b :: 1, 0
x = [2, 3, 4, 5, 6]
i, x[i] = 4, 99 # i, x[4] :: 4, 99; variable 'i' does not need to have been previously assigned
c = 8 # variable 'c' must be assigned first
c, d = 9, print(c) # c, d :: 9, None; prints 8
My confusion had to do with the fact that Python reassigned 'i'
(i.e., the list index) first, before assigning 99 to index 4 of list 'x'
.
While Python's documentation directly addresses this issue as following,
Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion.
I did not understand what it meant by "overlaps within the collection of assigned-to variables".
I see now that the parser will check to see if the indexing value for a given List has been reassigned before it assigns a new value to that index of the list.
Notes:
This is confirmed by the fact that, in this case, 'i'
did not need to be assigned first before it was used as a variable index, while for 'a'
it was necessary (otherwise, Python would throw an error).
For those curious, here's the PythonTutor visualization. Unfortunately, because it executes the assignment in one line (as it should), one cannot really see how Python interprets the statement.
This opacity of execution would be further compounded in the case of a user who had previously assigned i to an integer, and intended to use that previous integer as an index, and not the new value.
By the way, this is my first time asking a question, so I don't have the necessary reputation to post my own answer. Please feel free to provide any constructive advice on how I can improve any future questions I may ask, or on how I might better contribute to this community. Thanks.