Why Python does *SLICING* the way it does??

Raymond Hettinger vze4rx4y at verizon.net
Wed Apr 20 02:36:42 EDT 2005


<seberino at spawar.navy.mil>
> Many people I know ask why Python does slicing the way it does.....

Half open intervals are just one way of doing things.  Each approach has its own
merits and issues.

Python's way has some useful properties:

* s == s[:i] + s[i:]

* len(s[i:j]) == j-i     # if s is long enough


OTOH, it has some aspects that bite:

* It is awkward with negative strides such as with s[4:2:-1].  This was the
principal reason for introducing the reversed() function.

* It makes some people cringe when they first see it (you're obviously in that
group).


I suspect that whether it feels natural depends on your previous background and
whether you're working in an environment with arrays indexed from one or from
zero.  For instance, C programmers are used to seeing code like:   for(i=0 ;
i<n; i++) a[i]=f(i);   In contrast, a BASIC programmer may be used to FOR I = 1
to N:  a[I]=f(I); NEXT.    Hence, the C coders may find Python's a[:n] to be
more natural than BASIC programmers.

As long as a language is consistent about its approach, you just get used to it
and it stops being an issue after a few days.


Raymond Hettinger





More information about the Python-list mailing list