Closed sanjundong closed 6 years ago
This is how Python works. Please see the official documentation at https://docs.python.org/3/reference/simple_stmts.html#assignment-statements, specifically the following line:
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. For instance, the following program prints [0, 2]:
x = [0, 1]
i = 0
i, x[i] = 1, 2 # i is updated, then x[i] is updated
print(x)
Stack Overflow may be better suited to explain the details of Python assignment than we are.
For what its worth, if an (unimaginative) interviewer ever asks you the cliched question "How do you swap two variables without a temp variable", you just discovered the (trivial) Python answer.
Also, protip: use triple backticks
code
for code
blocks so they show up properly.
Description
What steps will reproduce the problem?
the program is like this:
the result is like:
but when i change the program like this
the result is like
so i think something is wrong!
Version and main components
Dependencies