Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List slice assignment with resize using negative indices [duplicate]

If I do this:

p=list(range(10))
p[2:6:1]=['a','b']

I get p=[0, 1, 'a', 'b', 6, 7, 8, 9] which means Python is replacing the the elements indexed 2-5 with the new list ['a','b'].

Now when, I do

p=list(range(10))
p[-2:-6:-1]=['a','b']

Python says ValueError: attempt to assign sequence of size 2 to extended slice of size 4

Why does it resize the list in the first case but not the second?

like image 816
Nachiket Avatar asked Jun 26 '20 13:06

Nachiket


2 Answers

This is expected behavior for extended slices. As you have discovered, it requires the same number of elements to be assigned to the slice. Here's documentation that refers to the issue.

It becomes more obvious why if instead you sliced p[1:5:2]. It's not a nice contiguous block that you can easily resize.

p[2:6:1] works because it's essentially a regular slice, ie p[2:6].

like image 178
busybear Avatar answered Nov 10 '22 01:11

busybear


I don't know the exact inner working of python list slicing, but it probably has something to do with the fact that p[-2:-6:-1] works backwards through the list instead of forwards.

If you want a quick fix, use: p[-6:-2:1] = ['a', 'b']

That way, you'll work from 'left to right' again.

like image 22
Tim J Avatar answered Nov 10 '22 02:11

Tim J