[docs] It may be a bug
Julien Palard
julien at palard.fr
Wed May 22 05:29:43 EDT 2019
Hi Jorge,
> just to report last lines results seems to obtain some extra numbers. it may be a bug
Slices in Python starts with an inclusive bound and end with an exclusive bound.
Quoting the documentations, s[i:j] is:
> The slice of s from i to j is defined as the sequence of items with index k such that `i <= k < j`
Given:
alist = list(range(10))
We can see that:
>>> alist[2:5]
[2, 3, 4]
>>> alist[5:2]
[]
Note that the second one, "from 5 to 2" is empty, yet starts at position 5, so when we assign to it, it will "erase" no values, yet have a place to put new values:
In this case, we're replacing all items of index k such as 2 <= k < 5, so index 2, 3, 4, so we're replacing 3 items by two items, the resulting length is 9:
>>> alist = list(range(10))
>>> alist[2:5] = 'a', 'b'
>>> alist
[0, 1, 'a', 'b', 5, 6, 7, 8, 9]
Here we're replacing all items of index k such as 5 <= k < 2, which can't exist, so we're replacing 0 items by two items, the resulting length is 12, note that they are not inserted randomly, they are inserted at the index where the empty slice starts:
>>> alist = list(range(10))
>>> alist[5:2] = 'a', 'b'
>>> alist
[0, 1, 2, 3, 4, 'a', 'b', 5, 6, 7, 8, 9]
In your example:
>>> v = []
>>> v[0:5]=6,7,8,9,0
>>> v[-1]=6,7
>>> v
[6, 7, 8, 9, (6, 7)]
>>> v[-1:-5] # An empty slice, so assigning to it will only add elements at position -1
[]
>>> v[-1:-5]='a','b','c','d','e'
>>> v
[6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', (6, 7)]
>>> v[-5:-1] # A non empty slice, so assigning to it will replace b, c, d, and e with A, B, C, D and E
['b', 'c', 'd', 'e']
>>> v[-5:-1]='A','B','C','D','E'
>>> v
[6, 7, 8, 9, 'a', 'A', 'B', 'C', 'D', 'E', (6, 7)]
Does it helps?
Bests,
--
Julien Palard
https://mdk.fr
More information about the docs
mailing list