classification
Title: Swap doesn't work in some circumstances
Type: behavior Stage: resolved
Components: macOS Versions: Python 3.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Ikaros, ned.deily, rhettinger, ronaldoussoren
Priority: normal Keywords:

Created on 2017-06-22 05:38 by Ikaros, last changed 2017-06-22 06:17 by rhettinger. This issue is now closed.

Messages (2)
msg296614 - (view) Author: Hang Liao (Ikaros) Date: 2017-06-22 05:38
Suppose I have two lists 
L1 = [1,3,2,4], L2 = [1,3,2,4]
L1[1], L1[2] = L1[2], L1[1]
This gives me L1 = [1,2,3,4]
However, if I write
L2[1], L2[L2[1] - 1] = L2[L2[1] - 1], L2[1]
This gives me back the same L2 = [1,3,2,4]
I am not sure if this is a mistake ... If it is what it intended to do please tell me.
msg296615 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2017-06-22 06:17
This is the expected behavior.
The assignments are made left-to-right.
The first use of L2[1] is updated BEFORE the second use as index.

The assignments are equivalent to:
==================================
>>> L1 = [1,3,2,4]
>>> L2 = [1,3,2,4]
>>> tup = L2[L2[1] - 1], L2[1]
>>> tup
(2, 3)
>>> L2[1] = tup[0]
>>> L2[L2[1] - 1] = tup[1]
>>> L2
[1, 3, 2, 4]

Which is the same as you observed
=================================
>>> L1 = [1,3,2,4]
>>> L2 = [1,3,2,4]
>>> L2[1], L2[L2[1] - 1] = L2[L2[1] - 1], L2[1]
>>> L2
[1, 3, 2, 4]

The core issue is that L2[1] is being used twice during the series of assignments.  First it gets updated with L2[1] = 3.  Then L2[1] is used again AFTER it has been updated.
History
Date User Action Args
2017-06-22 06:17:39rhettingersetstatus: open -> closed

nosy: + rhettinger
messages: + msg296615

resolution: not a bug
stage: resolved
2017-06-22 05:38:50Ikaroscreate