Tuple unpacking order changes values assigned

前端 未结 4 1490
温柔的废话
温柔的废话 2020-12-03 06:36

I think the two are identical.

nums = [1, 2, 0]    
nums[nums[0]], nums[0] = nums[0], nums[nums[0]]    
print nums  # [2, 1, 0]

nums = [1, 2, 0]    
nums[0]         


        
4条回答
  •  攒了一身酷
    2020-12-03 07:19

    In the first example, what happens is nums[1] gets set to 1, and then nums[0] gets set to 2, as you might expect.

    In the second example, nums[0] gets set to 2, and then nums[2] gets set to 1. This is because, in this case, the left hand side nums[nums[0]] is really referencing nums[2] when the assignment happens, because nums[0] had just been set to 2.

提交回复
热议问题