What are the steps that Python actually does to assign multiple variables at one line?
I use to do A[0], A[1] = A[1], A[0] to swap, but recently I got a bug when assigning a linked list.
# insert self->node->...
def insert_next(self, node):
node.next, node.prev = self.next, self
self.next, self.next.prev = node, node
self.next
become node
earlier than I expected, so the assign become
self.next, node.next = node, node
However, if I do
self.next.prev, self.next = node, node
It works!
I "assume" the steps are
1. cache values at the right side
2. assign to left side one by one, left to right
not
1. cache values at the right side
2. cache the ref at the left side
2. assign to ref one by one, left to right
So, what are the steps?
Multiple assignment in Python: Assign multiple values or the same value to multiple variables. In Python, use the = operator to assign values to variables. You can assign values to multiple variables on one line.
Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.
Multiple variable assignment is also known as tuple unpacking or iterable unpacking. It allows us to assign multiple variables at the same time in one single line of code. In the example above, we assigned three string values to three variables in one shot. As the output shows, the assignment works as we expect.
The code demonstrates that simultaneous assignment really is simultaneous. The value for a does not change before the value of b , so b gets the original value of a , and we can switch the values without using an interim step of creating a temporary (and otherwise useless) variable.
There's something called "expansion assignment" in Python.
Long story short, you can expand an iterable with assignment. For example, this code evaluates and expands the right side, which is actually a tuple, and assigns it to the left side:
a, b = 3, 5
Or
tup = (3, 5)
a, b = tup
This means in Python you can exchange two variables with one line:
a, b = b, a
It evaluates the right side, creates a tuple (b, a)
, then expands the tuple and assigns to the left side.
There's a special rule that if any of the left-hand-side variables "overlap", the assignment goes left-to-right.
i = 0
l = [1, 3, 5, 7]
i, l[i] = 2, 0 # l == [1, 3, 0, 7] instead of [0, 3, 5, 7]
So in your code,
node.next, node.prev = self.next, self
This assignment is parallel, as node.next
and node.prev
don't "overlap". But for the next line:
self.next, self.next.prev = node, node
As self.next.prev
depends on self.next
, they "overlap", thus self.next
is assigned first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With