Why is extended slice assignment less flexible than regular slice assignment?

隐身守侯 提交于 2019-12-01 10:40:55

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 are 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!