Reman - 1 year ago 112

Python Question

I know that you can swap 2 single indexes in Python

`r = ['1', '2', '3', '4', '5', '6', '7', '8']`

r[2], r[4] = r[4], r[2]

output:

`['1', '2', '5', '4', '3', '6', '7', '8']`

But why can't you swap 2 slices of indexes in python?

`r = ['1', '2', '3', '4', '5', '6', '7', '8']`

I want to swap the numbers 3 + 4 with 5 + 6 + 7 in r:

`r[2:4], r[4:7] = r[4:7], r[2:4]`

output:

`['1', '2', '5', '6', '3', '4', '7', '8']`

expected output:

`['1', '2', '5', '6', '7', '3', '4', '8']`

What did I wrong?

output:

Answer Source

The slicing is working as it should. You are replacing slices of different lengths. `r[2:4]`

is two items, and `r[4:7]`

is three items.

```
>>> r = ['1', '2', '3', '4', '5', '6', '7', '8']
>>> r[2:4]
['3', '4']
>>> r[4:7]
['5', '6', '7']
```

So when `['3', '4']`

is replaced, it can only fit `['5', '6']`

, and when `['5', '6', '7']`

is replaced, it only gets `['3', '4']`

. So you have `['1', '2',`

, then the next two elements are the first two elements from `['5', '6', '7']`

which is just `['5', '6'`

, then the two elements from `['3', '4'`

go next, then the remaining `'7', '8']`

.

If you want to replace the slices, you have to start slices at the right places and allocate an appropriate size in the array for each slice:

```
>>> r = ['1', '2', '3', '4', '5', '6', '7', '8']
>>> r[2:5], r[5:7] = r[4:7], r[2:4]
>>> r
['1', '2', '5', '6', '7', '3', '4', '8']
old index: 4 5 6 2 3
new index: 2 3 4 5 6
```