as the title says Im trying to swap the position of item on a list.
Like this:
A = [1,2,3,4,5,6] #original list
i,k,j,w = [0,2,3,6] #indexes
A[i:k], A[j:w] = A[j:w], A[i:k]
#expected A: [4,5,6,3,1,2]
print(A)
A: [4,5,6,1,2,6] #six is repeated and I`ve lost the item 3.
I have tried things like:
A[i:k+1], A[j:w-1] = A[j:w] , A[i:k]
and so on, but none of them worked.
Is there a way to do this in python?
>Solution :
Remember, A[0:2] includes only elements at index 0 and 1, 2 means till index 2 but not element at index 2.
So when you assign A[0:2] A[3:6] you are actually replacing 2 elements of list with three elements.
Another approach can be
A = A[j:w]+ A[k:j]+ A[i:k]
Your approach was neglecting the element at index 2 which was 3.