There I was, all this time, under the impression that a, b, c = c, a, b
is the same as a, c, b = c, b, a
... I thought this was a way to assign variables at the same time so you don't have to create a bunch of temp vars. But apparently they're different because one breaks my code.
Here's my original/working implementation:
class Node:
def __init__(self, v = None, next = None):
self.v = v
self.next = next
def __repr__(self):
return "Node(v=%r, nextV=%r)" % (self.v, self.next.v if self.next else None)
a = Node(1)
b = Node(2)
a.next = b
def flip(nodeA, nodeB):
nodeB, nodeA.next, nodeA = nodeA, nodeB, nodeA.next
return (nodeA, nodeB)
a, b = flip(a, b)
print "A=%r; B=%r" % (a, b)
Its correct/intended behavior is to swap the two nodes in a linked list, as shown by the output below:
A=Node(v=2, nextV=None); B=Node(v=1, nextV=2)
However, if I reorder the flip function like so:
def flip(nodeA, nodeB):
nodeB, nodeA, nodeA.next = nodeA, nodeA.next, nodeB
return (nodeA, nodeB)
...that output is broken:
A=Node(v=2, nextV=2); B=Node(v=1, nextV=2)
Node A ended up with a pointer back to itself (its nextV
and v
are identical), so an attempt to follow this tree would recurse forever.
Why aren't these results identical? Shouldn't tuple unpacking behave as if all assignments happened simultaneously?