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:
The slicing is working as it should. You are replacing slices of different lengths.
r[2:4]
is two items, andr[4:7]
is three items.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:
Think of this:
as similar to this:
So, by the time it gets to the third line of that, the 4th element isn't what you think it is anymore... You replaced
'3', '4'
with'5', '6', '7'
, and now the[4:7]
slice starts with that'7'
.In your code:
You are assigning
r[4:7]
which have 3 elements tor[2:4]
which have only 2.In the code I posted:
r[4:7]
which is['5', '6', '7']
, replacesr[2:5]
which is['3', '4', '5']
r
resulting in['1', '2', '5', '6', '7', '6', '7', '8']
and then:
r[2:4]
which was['3', '4']
, replacesr[5:7]
which is['6', '7']
So final result being: