pythonmultiple-assignmentparallel-assignment

The mechanism behind multiple assignment in Python


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?


Solution

  • a, b = c, d
    

    is equivalent to

    temp = (c, d)
    a = temp[0]  # Expression a is evaluated here, not earlier
    b = temp[1]  # Expression b is evaluated here, not earlier
    

    Personally I would recommend to write complex assignments explicitly with temporary variables as you showed it.

    Another way is to carefully choose the order of the elements in the assignment:

    nums[nums[0]], nums[0] = nums[0], nums[nums[0]]
    

    Changes nums as you expect.