Why does Python allow out-of-range slice indexes for sequences?

前端 未结 2 738
迷失自我
迷失自我 2021-01-30 12:39

So I just came across what seems to me like a strange Python feature and wanted some clarification about it.

The following array manipulation somewhat makes sense:

2条回答
  •  萌比男神i
    2021-01-30 13:12

    The documentation has your answer:

    s[i:j]: slice of s from i to j (note (4))

    (4) The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

    The documentation of IndexError confirms this behavior:

    exception IndexError

    Raised when a sequence subscript is out of range. (Slice indices are silently truncated to fall in the allowed range; if an index is not an integer, TypeError is raised.)

    Essentially, stuff like p[20:100] is being reduced to p[len(p):len(p]. p[len(p):len(p] is an empty slice at the end of the list, and assigning a list to it will modify the end of the list to contain said list. Thus, it works like appending/extending the original list.

    This behavior is the same as what happens when you assign a list to an empty slice anywhere in the original list. For example:

    In [1]: p = [1, 2, 3, 4]
    
    In [2]: p[2:2] = [42, 42, 42]
    
    In [3]: p
    Out[3]: [1, 2, 42, 42, 42, 3, 4]
    

提交回复
热议问题