Tuple unpacking order changes values assigned

前端 未结 4 1516
温柔的废话
温柔的废话 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:08

    It's because of that python assignment priority is left to right.So in following code:

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

    It first assigned the nums[0] to nums[nums[0]] means nums[1]==1 and then since lists are mutable objects the nums would be :

    [1,1,0]
    

    and then nums[nums[0]] will be assigned to nums[0] which means nums[0]==2 and :

    nums = [2,1,0]
    

    And like so for second part.

    Note that the important point here is that list objects are mutable and when you change it in a segment of code it can be change in-place. thus it will affect of the rest of the code.

    Evaluation order

    Python evaluates expressions from left to right. Notice that while evaluating an assignment, the right-hand side is evaluated before the left-hand side.

提交回复
热议问题