mikl mikl - 3 months ago 11
Python Question

How to switch position of two items in a Python list?

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?

Answer
    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]
Comments