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 'password2'
and '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?
as a result of this if last element is greater than element at position
i
then they both get swapped .I am not an expert in python but you could try: say
above would give o/p as:
Given your specs, I'd use slice-assignment:
The right-hand side of the slice assignment is a "reversed slice" and could also be spelled:
if you find that more readable, as many would.
The simple Python swap looks like this:
Now all you need to do is figure what
i
is, and that can easily be done withindex
:How can it ever be longer than
That's just a plain swap using temporary storage.
you can use for example: