Swap subsets in the same list using Python

What's wrong with the code below? I am trying to swap two subsets of a list of strings.

>>> a = ['b', 'b', 'b', 'a', 'x', 'x', 'x', 'x', 'x', 'y']  
['b', 'b', 'b', 'a', 'x', 'x', 'x', 'x', 'x', 'y']
>>> a[4:9]
['x', 'x', 'x', 'x', 'x']
>>> a[9:10]  
['y']
>>> a[4:9], a[9:10] = a[9:10], a[4:9]
>>> a  
['b', 'b', 'b', 'a', 'y', 'y', 'x', 'x', 'x', 'x', 'x']

      

+3


source to share


2 answers


Consider two commands executed by your a[4:9], a[9:10] = a[9:10], a[4:9]



  • a[4:9] = a[9:10]

    takes the 5th, 6th, 7th, 8th indexes of the list and replaces them with the 9th index. the value 4 'x' becomes 1 'y' and that leaves you with ['b', 'b', 'b', 'a', 'y', 'y']

    (now the first y

    is the result of your swap and the second is just the end of your original list)
  • a[9:10] = a[4:9]

    takes the last index in your list and changes it to 5 'x' (which consists of 4: 9 indices of the original list), which results in ['b', 'b', 'b', 'a', 'y', 'y', 'x', 'x', 'x', 'x', 'x']

+1


source


explanation given by @ClsForCookies and here's the solution you can list below:



>>> a
['b', 'b', 'b', 'a', 'x', 'x', 'x', 'x', 'x', 'y']
>>> a = a[:4] + a[9:10] + a[4:9]
>>> a
['b', 'b', 'b', 'a', 'y', 'x', 'x', 'x', 'x', 'x']
>>> 

      

-1


source







All Articles