New submission from airwin:
Note 5 (at
<https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange>
for Python 2 and at
<https://docs.python.org/3/library/stdtypes.html#common-sequence-operations>
for Python 3) concerning s[i:j:k] (the slice of s from i to j with step k)
contains the following two sentences:
"The slice of s from i to j with step k is defined as the sequence of items
with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices
are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never
including j)."
That limit, "(j-i)/k" is demonstrably wrong when the integer division has a
non-zero remainder. For example, for i=0, j=3, and k=2, n must be less than
int(3/2) = 1 (i.e., the slice only has one element) according to that limit,
but in fact the slice has two elements in agreement with the second sentence
and which can be seen from the following python (2 or 3) code example:
>>> x = [0,1,2,3,4,5]
>>> x[0:3:2]
[0, 2]
The following Python result is also instructive for negative steps.
>>> y=[5,4,3,2,1,0]
>>> y[-1:-4:-2]
[0, 2]
For this case as well the result is consistent with the second sentence of the
documentation but inconsistent with the first sentence since according to that
limit = int((len-4 - (len-1))/-2) = int(3/2) = 1 implying only one element in
the slice in contradiction to the above result.
Therefore, I suggest removing the incorrect mathematical limit "(j-i)/k" from
note 5 by replacing the above two sentences as follows:
"The slice of s from i to j with positive or negative step k is defined as the
sequence of items with index x = i + n*k such that the indices are i, i+k,
i+2*k, i+3*k and so on, stopping when j is reached (but never including j)."
Alternatively, one could replace the current incorrect limit by the correct
mathmatical expression. My guess is the limit should be "(j-i)/k" when there
is a zero remainder for that division, and "(j-i)/k + 1" when there is a
non-zero remainder. That limit works for the above two examples, but I don't
know how to prove that in general for this integer limit case. Furthermore,
even if somebody else can provide that proof, I still think the above single
sentence documents the slice limits exactly, is simpler, and therefore is
preferred.
N.B. I am formally reporting this issue as a Python 3 bug but as shown above
the same two sentences occur in the Python 2 documentation so when this bug is
fixed for the Python 3 documentation it should also be consistently fixed for
Python 2.
--
assignee: docs@python
components: Documentation
messages: 280068
nosy: airwin, docs@python
priority: normal
severity: normal
status: open
title: Slice limit documentation is incorrect
versions: Python 3.7
___
Python tracker
<http://bugs.python.org/issue28614>
___
___
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com