Slicing [N::-1]
Robert Kern
robert.kern at gmail.com
Fri Mar 5 17:12:39 EST 2010
On 2010-03-05 13:10 PM, Robert Kern wrote:
> On 2010-03-05 12:28 PM, Steven D'Aprano wrote:
>> On Fri, 05 Mar 2010 18:12:05 +0000, Arnaud Delobelle wrote:
>>
>>>>>> l = range(10)
>>>>>> l
>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>>>> l[7::-1]
>>> [7, 6, 5, 4, 3, 2, 1, 0]
>>>>>> [l[i] for i in range(7, -1, -1)]
>>> [7, 6, 5, 4, 3, 2, 1, 0]
>>
>> Where does the first -1 come from? Slices are supposed to have default
>> values of 0 and len(seq):
>
> Rather, they have 0 and len(seq), respectively, when the step is
> positive, and len(seq)-1 and -1 when the step is negative.
Well, not entirely true. [N:-1:-1] obviously doesn't work for this. Rather,
leaving the second argument in the slice empty means "go to the end if step > 0
or go to the beginning if step < 0". There is no explicit translation of the
latter because there is no numerical index for the element before the first element.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-list
mailing list