Why does a variable disappear when swapping the list of the odd number of variables?

Viewed 47

Why does six disappear when swapping the list of the odd number of variables in the below code?

In [1]: A = [3, 8, 9, 7, 6]

In [2]: A[:2], A[2:] = A[2:],  A[:2]

In [3]: A
Out[3]: [9, 7, 3, 8]

In [4]: B = [3, 8, 9, 7, 6]

In [5]: B[2:] + B[:2]
Out[5]: [9, 7, 6, 3, 8]

In [6]: C = [3, 8, 9, 7]

In [7]: C[:2], C[2:] = C[2:],  C[:2]

In [8]: C
Out[8]: [9, 7, 3, 8]

1 Answers
A[:2], A[2:] = A[2:],  A[:2]

effectively resolves to:

# A = [3, 8, 9, 7, 6]
tmp1 = A[2:]  # tmp1 = [9, 7, 6]
tmp2 = A[:2]  # tmp2 = [3, 8]
A[:2] = tmp1  # A = [9, 7, 6, 9, 7, 6]
A[2:] = tmp2  # A = [9, 7, 3, 8]

List slicing is weird, and a larger slice can replace all the elements in a smaller slice, thus expanding the list. Similarly, a smaller slice can replace a larger slice, thus removing elements that used to be there.

That's what's happening here - the evaluation order, in which A[:2] gets fully evaluated before A[2:], means that the assignment to A[2:] ends up overwriting one of the values inserted by A[:2].

For a situation like this, you're better off using concatenation than multiple assignment, like you do with list B in your example.

Related