We all know multiple assignment can assign multiple variables at one time, and it is useful in swap. It works well in this situation:
nums = [2, 0, 1]
nums[0], nums[2] = nums[2], nums[0]
# nums=[1, 0, 2] directly, correct
, but it failed in more complex situation, such as:
nums = [2, 0, 1]
nums[0], nums[nums[0]] = nums[nums[0]], nums[0]
# nums=[1, 2, 1] directly, incorrect
nums = [2, 0, 1]
tmp = nums[0]
nums[0], nums[tmp] = nums[tmp], nums[0]
# nums=[1, 0, 2] with temporary variable, correct
It seems in nums[nums[0]], nums[0] will be assigned before, not at one time.
it also failed in complex linklist node swap, such as:
cur.next, cur.next.next.next, cur.next.next = cur.next.next, cur.next, cur.next.next.next
# directly, incorrect
pre = cur.next
post = cur.next.next
cur.next, post.next, pre.next = post, pre, post.next
# with temporary variable, correct
So I want to know the mechanism behind multiple assignment in Python, and what is the Best Practices for this, temporary variable is the only way?
c, b = b, cis not the same asa = b, c; c, b = a. I wish I could remember which other question had covered this. - Dan D.