On Tuesday, December 5, 2017 at 12:40:01 AM UTC+5:30, 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.


Data Structures have invariants.
Some of these are just side-notes… interesting, cute
Some are more fundamental, the raison d'être for the data structure

Whether the following inv is that fundamental or not I wont offer an opinion
It certainly seems important (to me)

Python slice inv:   (∀ n:ℤ, l:sequence | l[:n] + l[n:] == l)

Your preferred inv:   (∀ n:ℤ, l:sequence ∧ jason_caveat(n) | l[:n] + l[n:] == l)
  where
   def jason_caveat(n,l):
      return 0 ≤ n ≤ len(l)

Do you consider it arguable that your preferred invariant is at least
more heavy-weight if not downright clunkier?

Note I am not offering a view on this.

eg for zip python does this

>>> zip([1,2,3], [4,5,6,7,8])
[(1, 4), (2, 5), (3, 6)]

I find myself sometimes needing this

Sometimes needing it extended to the longer (with what??)

Sometimes needing your preferred behavior — an exception

On a more fundamental note:
def const(x): return 42

has the invariant that const(x) == 42 when x is well-defined
This is true for most mainstream languages

Lazy functional languages (like Haskell) make a big deal of not having the
definedness caveat.
People (like me) not quite on the FP bandwagon are conflicted on whether the
mathematical elegance is worth the computational mess
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to