Why is extended slice assignment less flexible tha

2020-03-25 01:04发布

问题:

According to the Python documentation on extended slices:

If you have a mutable sequence such as a list or an array you can assign to or delete an extended slice, but there are some differences between assignment to extended and regular slices. Assignment to a regular slice can be used to change the length of the sequence:

>>> a = range(3)
>>> a
[0, 1, 2]
>>> a[1:3] = [4, 5, 6]
>>> a
[0, 4, 5, 6]

Extended slices aren't this flexible. When assigning to an extended slice, the list on the right hand side of the statement must contain the same number of items as the slice it is replacing:

>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2

I do not understand why the "ordinary" slice method works but the "extended" slice method doesn't work. What differentiates an "ordinary" slice from an "extended" slice, and why does the "extended" slice method fail?

回答1:

It's a little easier to see the problem if you try to imagine how

a[::3] = [0, 1, 2]

would work with a 4-item list:

+---+---+---+---+   +   +---+
| a | b | c | d |       | ? |
+---+---+---+---+   +   +---+
  ^           ^           ^
+---+       +---+       +---+
| 0 |       | 1 |       | 2 |
+---+       +---+       +---+

We're trying to replace every third value, but our list isn't long enough, so if we went ahead anyway we'd end up with some kind of weird frankenstein list where some of the items don't actually exist. If someone then tried to access a[5] and got an IndexError (even though a[6] works normally), they'd get really confused.

Although you could technically get away with the a[::2] case by extending a by one, for the sake of consistency, Python bans all extended slicing assignments unless there's already a place for the value to go.

A regular slice always has a stride of one, so there's no chance of any gaps occurring, and so the assignment can safely be allowed.