Python swapping lists

后端 未结 3 741
灰色年华
灰色年华 2021-01-11 22:44

In python, when I assign a list to another, like:

a = [1,2,3]
b = a

Now b and a point to the same list. Now considering two lists,

3条回答
  •  独厮守ぢ
    2021-01-11 23:37

    Because Python assignment first evaluates the right-hand-side expression, then applies the result to the left-hand-side targets.

    So, first, Python creates (, ) as a tuple, then assigns the first item in that tuple to a, and the second item in that tuple to b. This swaps the references around neatly.

    You could expand the assignment to read it like this:

    tmp = b, a
    a = tmp[0]
    b = tmp[1]
    

提交回复
热议问题