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:
The documentation has your answer:
s[i:j]
: slice ofs
fromi
toj
(note (4))(4) The slice of
s
fromi
toj
is defined as the sequence of items with indexk
such thati <= k < j
. Ifi
orj
is greater thanlen(s)
, uselen(s)
. Ifi
is omitted orNone
, use0
. Ifj
is omitted orNone
, uselen(s)
. Ifi
is greater than or equal toj
, 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]