I understand that somelist[len(somelist)]
cannot access an index that is outside of the defined list - this makes sense.
But why then does Python allow you to do somelist[len(somelist):]
?
I've even read that somelist[len(somelist):] = [1]
is equivalent to somelist.append(1)
But why does slice notation change the fact that the index "len(somelist)" is still outside the range of the list?
Here's something from the documentation. There are specific rules around slicing of any iterable; of particular note is #4, emphasis mine:
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.
There's nothing at the index len(somelist)
(list indices start at 0 in python). Therefore, trying to access a non-existing element raises an error.
However, list slicing (with the myList[i:]
syntax) returns a new list containing the elements including and after i
. Since there are no elements in the list at index i
(or after), an empty list is returned
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With