Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

People also ask

How do you change the place of two elements in a list in Python?

To swap two list elements x and y by value, get the index of their first occurrences using the list. index(x) and list. index(y) methods and assign the result to variables i and j , respectively. Then apply the multiple assignment expression lst[i], lst[j] = lst[j], lst[i] to swap the elements.

How do you change the position of an element in a list in Python?

Method #1 : Using append() + pop() + index() This particular functionality can be performed in one line by combining these functions. The append function adds the element removed by pop function using the index provided by index function.

Can you swap items in a list Python?

Use the Assignment Operator to Swap Elements of a List in Python. One of the easiest and most commonly used methods to swap a list of elements is through the assignment operator and comma.

How do you change the order of a list in Python?

Python lists can be reversed in-place with the list. reverse() method. This is a great option to reverse the order of a list (or any mutable sequence) in Python. It modifies the original container in-place which means no additional memory is required.


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 index:

i = foo.index("password2")

Given your specs, I'd use slice-assignment:

>>> L = ['title', 'email', 'password2', 'password1', 'first_name', 'last_name', 'next', 'newsletter']
>>> i = L.index('password2')
>>> L[i:i+2] = L[i+1:i-1:-1]
>>> L
['title', 'email', 'password1', 'password2', 'first_name', 'last_name', 'next', 'newsletter']

The right-hand side of the slice assignment is a "reversed slice" and could also be spelled:

L[i:i+2] = reversed(L[i:i+2])

if you find that more readable, as many would.


How can it ever be longer than

tmp = my_list[indexOfPwd2]
my_list[indexOfPwd2] = my_list[indexOfPwd2 + 1]
my_list[indexOfPwd2 + 1] = tmp

That's just a plain swap using temporary storage.


for i in range(len(arr)):
    if l[-1] > l[i]:
        l[-1], l[i] = l[i], l[-1]
        break

as a result of this if last element is greater than element at position i then they both get swapped .