why won't slicing lists raise IndexError?
MRAB
python at mrabarnett.plus.com
Mon Dec 4 16:52:00 EST 2017
On 2017-12-04 21:22, Jason Maldonis wrote:
>>
>> >> 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.
>> >>
>> >
>> > The only relevant bit I found in that link is: "However, out of range
>> > slice indexes are handled gracefully when used for slicing". I do
>> > understand _how_ slices work, but I would really like to know a bit more
>> > about why slices will never throw out-of-bounds IndexErrors.
>>
>> That's what "handled gracefully" means. Instead of throwing, they get
>> clamped.
>>
>> ChrisA
>
>
> Cool! Why? I know I'm being a bit pedantic here, but I truly would like
> to understand _why_ slices get clamped. I've been writing python code
> every day for almost 7 years, so usually I can figure stuff like this out,
> but I'm struggling here and would really appreciate some insight.
>
Here's an example:
You have a string of at least n characters.
You want to get the first n characters and leave the remainder.
The first n characters is my_string[ : n].
The remainder is my_string[n : ].
What if len(my_string) == n?
Wouldn't my_string[n : ] raise an IndexError?
Another example:
You want at most n characters of my_string.
What if len(my_string) < n?
my_string[ : n] would raise an IndexError.
You'd need to do my_string[ : min(n, len(my_string))].
Although Python's slicing behaviour doesn't help in your use-case, in
the majority of cases it does.
More information about the Python-list
mailing list