why won't slicing lists raise IndexError?
MRAB
python at mrabarnett.plus.com
Mon Dec 4 14:46:19 EST 2017
On 2017-12-04 18:54, 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.
>
> Quick example:
>
> my_list = [1, 2, 3]
> my_list[:100] # does not raise an IndexError, but instead returns the full
> list
>
> 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.
>
Have you ever used a language that does that?
I have.
The String class in the C# language does that, and it's /really/ annoying.
I have to add extra code to prevent such exceptions.
In practice, I find that the way that Python does it is much nicer. (And
Python isn't unique in this respect, either.)
More information about the Python-list
mailing list