I haven’t been able to find a good solution for this problem on the net (probably because switch, position, list and Python are all such overloaded words).
It’s rather simple – I have this list:
['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter']
I’d like to switch position of
'password1' – not knowing their exact position, only that they’re right next to one another and
password2 is first.
I’ve accomplished this with some rather long-winded list-subscripting, but I wondered its possible to come up with something a bit more elegant?
i = ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter'] a, b = i.index('password2'), i.index('password1') i[b], i[a] = i[a], i[b]
The simple Python swap looks like this:
foo[i], foo[j] = foo[j], foo[i]
Now all you need to do is figure what
i is, and that can easily be done with
i = foo.index("password2")