Slicing [N::-1]

Robert Kern robert.kern at gmail.com
Fri Mar 5 14:10:18 EST 2010


On 2010年03月05日 12:28 PM, Steven D'Aprano wrote:
> On 2010年3月05日 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.
>>>> l[7::1]
> [7, 8, 9]
>>>> [l[i] for i in range(7, len(l), 1)]
> [7, 8, 9]
>>>> [l[i] for i in range(7, len(l), -1)]
> []
>>> I don't believe the actual behaviour is documented anywhere.

True, I don't think it is.
-- 
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

AltStyle によって変換されたページ (->オリジナル) /