This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Slicing strings out of bounds does not raise IndexError
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.6, Python 3.4, Python 3.5, Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Elizacat, eryksun
Priority: normal Keywords:

Created on 2016-07-11 01:04 by Elizacat, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (2)
msg270147 - (view) Author: Elizabeth Myers (Elizacat) * Date: 2016-07-11 01:04
When slicing strings, IndexError is not raised when the slices are out of bounds, even for negative indexes. Like so:

>>> "test"[-1000:1000]
'test'

>>> "test"[-1000:1]
't'

>>> ""[-100:100]
''

This seems more like a bug than useful behaviour to me.
msg270157 - (view) Author: Eryk Sun (eryksun) * (Python triager) Date: 2016-07-11 04:24
This is documented behavior for the built-in sequence types [1], and it's also mentioned in the tutorial [2].

The indices() method of a slice object shows the resolved bounds for given sequence length:

    >>> slice(-1000, 1000, 1).indices(4)
    (0, 4, 1)
    >>> slice(None, None, 1).indices(4)
    (0, 4, 1)

    >>> slice(1000, -1000, -1).indices(4)
    (3, -1, -1)
    >>> slice(None, None, -1).indices(4)
    (3, -1, -1)

The rules apply the same to list, tuple, and range sequences:

    >>> [1, 2, 3, 4][-1000:1000]
    [1, 2, 3, 4]
    >>> (1, 2, 3, 4)[-1000:1]
    (1,)
    >>> range(0)[-100:100]
    range(0, 0)

[1]: https://docs.python.org/3/library/stdtypes.html#common-sequence-operations
[2]: https://docs.python.org/3/tutorial/introduction.html#strings
History
Date User Action Args
2022-04-11 14:58:33adminsetgithub: 71666
2016-07-11 04:24:42eryksunsetstatus: open -> closed

nosy: + eryksun
messages: + msg270157

resolution: not a bug
stage: resolved
2016-07-11 01:04:55Elizacatsetcomponents: + Interpreter Core
2016-07-11 01:04:20Elizacatsettype: behavior
2016-07-11 01:04:08Elizacatcreate