Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

swap sublist of different length in python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading