why won't slicing lists raise IndexError?

breamoreboy at gmail.com breamoreboy at gmail.com
Mon Dec 4 14:19:03 EST 2017


On Monday, December 4, 2017 at 7:10:01 PM UTC, 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.

This is explained in the Python tutorial for strings https://docs.python.org/3/tutorial/introduction.html#strings, as a list is a sequence just like a string it will act in exactly the same way.

--
Kindest regards.

Mark Lawrence.



More information about the Python-list mailing list