Simple slicing question

Alex Martelli aleax at aleax.it
Mon Jan 14 08:39:26 EST 2002


"Nikhil R. Deshpande" <dnikhil at ip.eth.net> wrote in message
news:a1vejc$6ut$1 at news.vsnl.net.in...
    ...
> >>> a = [1, 2, 3]
> >>> a[100:200]
> []
>
> Why doesn't a[100:200] result in an IndexError?

Slicing is a very tolerant operation -- it will NEVER raise an
IndexError.  Slice-boundaries outside the sequence-boundaries
just result in an empty-slice, that's all.  And, why shouldn't
they?  The situations is very different for *indexing*, which
must return exactly one item, thus having no natural way to
indicate index-out-of-bounds... save for the exception.

This gives usable idioms for such tasks as "check whether S
is at least 4-long and the 4th character a Z":
    if S[3:4]=='Z':
rather than
    if len(S)>=4 and S[3]=='Z':

Some would prefer the latter as "more explicit"... I don't.


Alex






More information about the Python-list mailing list