Search code examples
pythonlistslice

Swap sublist of different length in Python


I’m trying to swap the position of items in 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.