Iterable Unpacking Evaluation Order

后端 未结 1 556
广开言路
广开言路 2021-01-25 15:10

I recently answered a question where a user was having trouble because they were appending a multi-dimensional array to another array, and it was brought to my attention in my a

相关标签:
1条回答
  • 2021-01-25 15:29

    The right side of the = is always evaluated first, in this case it is packing a tuple. That tuple is then unpacked when interpreting the left hand side. The left and right sides do not share knowledge of variables. The RHS becomes a value and then the LHS uses that value to assign to the variables (labels).

    In your example the values of x and y are determined after the RHS is evaluated. The unpacking then occurs left to right, so that board[x][y] has valid indices.

    Switching the order demonstrates the unpacking sequence:

    >>> board[x][y], x, y = move[2], move[0], move[1]
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-7-a984ef3168f8> in <module>()
    ----> 1 board[x][y], x, y = move[2], move[0], move[1]    
    NameError: name 'x' is not defined
    
    0 讨论(0)
提交回复
热议问题