Slicing [N::-1]

Gary Herron gherron at islandtraining.com
Fri Mar 5 22:05:20 EST 2010


Mensanator wrote:
> On Mar 5, 6:34 pm, Gary Herron <gher... at islandtraining.com> wrote:
>   
>> Mensanator wrote:
>>     
>>> On Mar 5, 3:42 pm, Gary Herron <gher... at islandtraining.com> wrote:
>>>       
>>>> Mensanator wrote:
>>>>         
>>>>> The only way to get a 0 from a reverse range() is to have a bound of
>>>>> -1.
>>>>>           
>>>> Not quite.  An empty second bound goes all the way to the zero index:
>>>>         
>>> Not the same thing. You're using the bounds of the slice index.
>>> I was refering to the bounds of the range() function.
>>>       
>>>>>> for a in range(9,-9,-1):print(a,end=' ')
>>>>>>             
>>> 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8
>>>       
>>> To get that to stop at 0, you use a -1 as the bounds:
>>>       
>>>>>> for a in range(9,-1,-1):print(a,end=' ')
>>>>>>             
>>> 9 8 7 6 5 4 3 2 1 0
>>>       
>>> Your slice notation only works if the last (first?) number in
>>> the range happens to be 0. What if the range bounds were variables?
>>> You may still want to force the range's last number to be 0 by
>>> using a constant like range(a,-1,-1) rather than just take
>>> the last number of range(a,b,-1) by using slice notation.
>>>       
>> All true  and valid of course, but I was just contridicting the "the
>> ONLY way to get a 0" (emphasis mine) part of the statement.
>>     
>
> Does it still contradict if you do not use the '::' as the OP
> requested?
>   

Not to my knowledge...  I believe your statement is true in all cases 
which explicitly state the stop value.


>   
>> Gary Herron
>>
>>
>>
>>
>>
>>     
>>>>  >>> range(9)[2::-1]
>>>> [2, 1, 0]
>>>>         
>>>> Gary Herron- Hide quoted text -
>>>>         
>> - Show quoted text -- Hide quoted text -
>>
>> - Show quoted text -
>>     
>
>   




More information about the Python-list mailing list