Alex Rivera | Logout

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

Asked 2013-03-18T05:33:59.800
8

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?

Edit
Report

1 Answer

1

From the Python docs:

Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

So an index > list size is automatically corrected, and somelist[len(somelist):] returns the elements after the last one, ie nada.

answered 2013-03-18T05:40:54.983

Your Answer