2 ms·
a[1] has to raise an IndexError because there's no return value it could use to otherwise communicate the item doesn't exist. Any such value could itself be a m
by js2 3y ago
a[1] has to raise an IndexError because there's no return value it could use to otherwise communicate the item doesn't exist. Any such value could itself be a member of the sequence. To behave otherwise, Python would have to define a sentinel value that isn't allowed to be a member of a sequence.
When using slice notation, the return value is a sequence, so returning a zero-length sequence is sufficient to communicate you asked for more items than exist.
It may be surprising, but it almost always leads to more ergonomic code.
https://discuss.python.org/t/why-isnt-slicing-out-of-range/ https://discuss.python.org/t/why-isnt-slicing-out-of-range/