why won't slicing lists raise IndexError?

Random832 random832 at fastmail.com
Sun Dec 3 21:31:16 EST 2017


On Mon, Dec 4, 2017, at 13:54, Jason Maldonis wrote:
> Is there any background on why that doesn't raise an IndexError? Knowing
> that might help me design my extended list class better. For my specific
> use case, it would simplify my code (and prevent `if isinstance(item,
> slice)` checks) if the slicing raised an IndexError in the example I
> gave.

Slicing (of strings, lists, tuples, anyway) never raises an IndexError. If the
start is out of range it will return an empty list. I don't know. As for "why",
 it's just how the operation was designed. Perhaps it was considered that an
exception isn't needed because there's no ambiguity (i.e. there's no other
reason a slice operation can return a list shorter than the length implied by
the slice parameters).

Why would this simplify your code? What are you doing that would benefit from
an IndexError here?




More information about the Python-list mailing list