0

For example, I want to swap the two items in the list:

a = ['h','e']
a[a.index('h')], a[a.index('e')] = a[a.index('e')], a[a.index('h')]

but this doesn't seem to do anything. On the other hand

a[0], a[1] = a[1], a[0]

works. So why the discrepancy?

Vim
  • 1,436
  • 2
  • 19
  • 32
  • @abccd this indeed works for this particular `a`, but can't be generalised when I want to swap two arbitrary items in a long list. – Vim Mar 23 '17 at 10:20
  • sounds very much like http://stackoverflow.com/questions/40272594/python-multiple-assignment-issue-list/40273033 and other questions – aka.nice Mar 23 '17 at 10:21
  • Get the two indices `i` and `j` first with `l.index(thing)`, then `l[i], l[j] = l[j], l[i]` will work fine. – jonrsharpe Mar 23 '17 at 10:24
  • @jonrsharpe yes indeed, which makes the discrepancy even more curious. – Vim Mar 23 '17 at 10:25
  • No it doesn't. The assignment is left-to-right, per the docs and the various linked questions. Getting the indices first avoids the list having already been modified when you get the second index. – jonrsharpe Mar 23 '17 at 10:26
  • `a[0] = a[1]` and `a = [a[1],a[1]]` how to protect index and values ? `a = [1,2]; b= a[1],a[0]; a = b; del b;` **forget using temp values !** – dsgdfg Mar 23 '17 at 10:28
  • Your style maybe work load `list` to an `iterator`, like `for` ! – dsgdfg Mar 23 '17 at 10:30
  • No I'll never use this bad style again since it's too dangerous fiddling with these minutiae. I am just being curious asking this question. – Vim Mar 23 '17 at 10:36

0 Answers0