3

Why the first one gives the wrong swap like this? Thanks a lot.

a = [-1,4,3,1]
a[3], a[a[3]-1] = a[a[3]-1], a[3]
print a #gives [-1, 4, 1, -1], which is wrong


a = [-1,4,3,1]
a[a[3]-1], a[3] = a[3], a[a[3]-1]
print a #gives [1, 4, 3, -1]
CindyG
  • 109
  • 3
  • Yeah, the LHS behavior of Python multiple assignment doesn't work very well in edge cases. Changing it now would break backward compatibility. – user2357112 Dec 18 '18 at 23:39
  • It's not a bug - it's working as designed - but the evaluation order design would have been more intuitive if it didn't interleave evaluation and assignment so much. – user2357112 Dec 18 '18 at 23:43
  • @user2357112 I don't follow exactly what makes this a "edge case" though? – roganjosh Dec 18 '18 at 23:46
  • @roganjosh: Dependencies between assignment targets. – user2357112 Dec 18 '18 at 23:48
  • One could always fix it with `t = a[a[3]-1], a[3]; a[3], a[a[3]-1] = t` – Dan D. Dec 18 '18 at 23:49
  • @user2357112 am I correct in thinking that numpy had a shot at fixing this and presumably chose to stay consistent with Python or are they strictly bound to this unpacking behaviour? I half expected not to be able to recreate with an array.. – roganjosh Dec 18 '18 at 23:57
  • @roganjosh: NumPy can't change Python's evaluation order. There doesn't seem to be any way they could have plausibly changed this behavior. – user2357112 Dec 18 '18 at 23:59

0 Answers0