why won't slicing lists raise IndexError?

Terry Reedy tjreedy at udel.edu
Mon Dec 4 17:01:50 EST 2017


On 12/4/2017 1:54 PM, Jason Maldonis wrote:
> I was extending a `list` and am wondering why slicing lists will never
> raise an IndexError, even if the `slice.stop` value if greater than the
> list length.

> Is there any background on why that doesn't raise an IndexError?

Slicing is perhaps most commonly used on strings, and clamping is 
probably most useful for strings.

Example 1:  s[0:k] gets the k or fewer initial characters of the string, 
perhaps to put in a fixed-width display or storage field.

Example 2: below are two equivalent (I believe) code snippets.

try:
     item = seq[n]
except IndexError
     do_without_item()
else:
     process(item)

item = seq[n:n+1]
if item:
     process(item)
else:
     do_without_item()

Many prefer the second.  Note that moving process(item) in the first 
into the try clause makes the two non-equivalent.

Example 3:

'if s[k:k+1] in okset' versus 'if len(s) >= k+1 and s[k] in okset'.

There are many examples like this where is slicing did not clamp, the 
user would have to reproduce some of the logic done by slices.

-- 
Terry Jan Reedy




More information about the Python-list mailing list