why won't slicing lists raise IndexError?

Rick Johnson rantingrickjohnson at gmail.com
Mon Dec 4 16:37:22 EST 2017


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

That's a feature dude, not a bug.

In this case, it only seems illogical because you already
know the extents of the buffer, and that's because you
created it.

However, outside of hand-stiched arts and crafts projects in
the interactive basement of your parent's home, you have no
way of knowing how large a buffer may be in the wild. And
many times, you just need a "transparent slice" from it.

What does "transparent slice" mean, you ask?

Well, for example, (contrived example here) consider a case
where you want the first N chars from a collection of N
strings. In such a case, even if `s[:100]` returns a null
string from the first target, 55 chars from the next target,
99 chars from the next target, and so on and so forth -- you
don't care -- because all you want is a "transparent slice"
of each target string.  And the onerous exception handling
required to deal with disparate buffer lengths would just
get in the way of doing that job _cleanly_.

Now, some might argue that such a feature breaks the Python
Zen. Okay. Let's investigate, shall we>

ZEN SAYS: "SPECIAL CASES ARE NOT SPECIAL ENOUGH TO BREAK THE RULES"

    Hmm, with this "feature" being applicable to so many
    problems, i would hardly consider it to be a "special case".

Next!

ZEN SAYS: "EXPLICIT IS BETTER THAN IMPLICIT"

    Hmm, this one may be difficult to overcome, but we need to
    conduct a cost-benefit analysis _first_. And, since i have
    not encountered, in my many years of writing Python code,
    even one instance of a negative side-effect to this
    transparent slicing feature, and, furthermore, i have not
    even ~heard~ of one instance of this feature causing havoc,
    i will, at this time, and until compelling evidence is
    provided to the contrary, conclude that the Zen is wrong in
    this case.

    *GASP*

Next!

ZEN SAYS: "ALTHOUGH PRACTICALITY BEATS PURITY. ERRORS SHOULD NEVER PASS SILENTLY. UNLESS EXPLICITLY SILENCED."

    Some might accuse this feature of "masking errors", however,
    i don't agree, And while technically speaking --  yes -- a
    requested slice range which overlaps the actual physical
    boundaries of a target buffer _is_ violating the physical
    laws which govern disparate entities existing in a material
    universe, code exists beyond the material universe, So this
    beef boils down to a petty qualm over semantics.

Next!




More information about the Python-list mailing list