slicing insert question, L[1:1]

不羁的心 提交于 2019-12-17 20:26:56

问题


practising some python, which is a pretty easy language to grab up.

I have

>>> L = [1,2,3,4]
>>> L[1:1] = [1,2,3]
>>> L
[1, 1, 2, 3, 2, 3, 4]

so on line two actually L[1:1] is empty list, but how can python understand that insert the [1,2,3] list to starting from 1. I guess there is some internals which is not transparent to us, here apparently, I guess L[1:1] returns a reference to index 1 even if that returns an empty list...

Best wishes, Umut


回答1:


L[1:1] means the slice of the list L starting at index 1 (the second element), up to but not including index 1. So it is an empty list. On the right-hand side of an assignment, it is simply an anonymous empty list. But on the left-hand side, the assignment knows where the slice has been made, and can splice in the new list value into the proper place.




回答2:


Slicing behaves differently depending on whether it's on the left- or right-hand side of an expression. When it's on the left side, it doesn't return a list - instead, it behaves as a slice object, which knows more about slices and has assignment specifically overridden to operate as insertion.




回答3:


The official Python Tutorial explains it best, in my opinion. The end of Chapter 3.1.2 has the following diagram:

 +---+---+---+---+---+
 | H | e | l | p | A |
 +---+---+---+---+---+
 0   1   2   3   4   5

What this illustrates is that you can think of the indices as pointing BETWEEN the elements. So in this illustration, if specifying a slice [1:1], you are actually referring to the space between H and e, but not including them.

If you wanted to overwrite H and e, you would specify the slice [0:2].



来源:https://stackoverflow.com/questions/4574487/slicing-insert-question-l11

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