Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does somelist[len(somelist)] generate an IndexError but not somelist[len(somelist):]?

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?

like image 587
Alex Krycek Avatar asked Mar 18 '13 05:03

Alex Krycek


2 Answers

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

like image 172
Makoto Avatar answered Nov 15 '22 05:11

Makoto


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

like image 40
inspectorG4dget Avatar answered Nov 15 '22 03:11

inspectorG4dget