Why can't I assign arbitrary iterability to an extended slice whose step is -1?

Python 3.2.3 (default, Apr 11 2012, 07:15:24) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> u = [4, 5, 6, 7, 8, 9] >>> u[1::1] = [3, 2, 1, 0] >>> u [4, 3, 2, 1, 0] >>> u[9:0:-1] = [8, 7, 6, 5] >>> u [4, 5, 6, 7, 8] >>> u[9:0:-1] = [16, 12, 8] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: attempt to assign sequence of size 3 to extended slice of size 4 >>> u [4, 5, 6, 7, 8] >>> 

Expected Behavior: An exception is not thrown for the final assignment operation; u should print on the last line as [4, 8, 12, 16] .

I can assign an extended slice whose step is 1, even if the iterability that I assign is "the wrong length". Why then can I not assign an extended slice whose step is -1, and does it work in an obvious way?

+6
source share
1 answer

I think creating an extended slice whose step 1 effectively acts like a regular slice, not an extended slice.

Extended fragments do not allow you to change the length of the sequence, as indicated here

If you have a mutable sequence, such as a list or an array, you can assign or remove an extended slice, but there are some differences between assigning to extended and regular slices. Appointment of a regular slice can be used to change the length of the sequence. Extended slices are not flexible. When assigning an extended fragment, the list on the right side of the instruction should contain the same number of elements as the slice that it replaces.

As to why it works this way, I can only guess that this is due to cases where there is no obvious behavior. Take this example:

 u = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] u[0:8:3] = [ 10, 11 ] 

How do you expect this to work? I think you could just replace 1 and 4 with 10 and 11, but what about 7? Will you leave him Delete it? Delete all remaining sequence after 7? Maybe it's just me, but this case does not seem too clear. I would suggest why this behavior is simply not allowed for extended snippets.

+3
source

Source: https://habr.com/ru/post/917693/


All Articles