Comparison problem

Alex Martelli aleax at mail.comcast.net
Sun Nov 27 03:06:33 CET 2005


Tom Anderson <twic at urchin.earth.li> wrote:
   ...
> But, more importantly, egad! What's the thinking behind having slicing
> behave like that? Anyone got any ideas? What's the use case, as seems to
> be the fashionable way of putting it these days? :)

Slicing has always been "soft" (it's OK to specify slice indices beyond
the boundaries) while indexing has always been "hard" (specifying an
index beyond the boundaries raises an exception).  It does allow simpler
and more concise expression of conditions on slices, without requiring
you to guard the test on the slice with another test on the sequence's
length.  For example, to say "those sublists of lists-of-lists bigL that
don't end in [...1,2,3]" you can code

[L for L in bigL if L[-3:] != [1,2,3]]

instead of

[L for L in bigL if len(L) < 3 or L[-3:] != [1,2,3]]

Introducing the endswith and startswith string methods lowered the
usefulness of soft slicing for such tests on strings (since it
subtracted some specific use cases), but not all sequences have such
specialized methods, and not all use cases of soft slicing are tests.
E.g., "remove the last character of s (if any)" can be compactly
expressed with "s=s[:-1]" rather than "s=s and s[:-1]" or more expansive
testing.  No big deal, but then again I don't recall any situation in
which getting an exception from slicing (as opposed to indexing) would
have helped me catch a bug faster.


Alex



More information about the Python-list mailing list