0

These would seem to be equivalent but according to the interperter they are not. I have been banging my head with this for along time

>>> a = '123456789'
>>> a[0:9]
'123456789'
>>> a[0:9:1]
'123456789'
>>> a[::1]
'123456789'
>>> a[::-1]
'987654321'
>>> a[0:9:-1]   #why is this not equivilent to a[::-1]
''
>>> 
4
Contributors
4
Replies
5
Views
4 Years
Discussion Span
Last Post by snippsat
0
a[0:9:-1]   #why is this not equivilent to a[::-1]

start at a[0], (then -1 = a[-1] which doesn't exist), and go in reverse order until the number is less than 9, which zero is. You want, a[end:start-1:-1], but why even try to reinvent the wheel that is already working.

Edited by woooee

0

I see where my logic was wrong. it apears that when slicing with a negative step, the start and endpoints need to be reversed

0

it apears that when slicing with a negative step, the start and endpoints need to be reversed

With negative step values,slicing will automatically step into in Alice in Wonderland reversed world.

Like this we can look at vaules for seq[start:stop:step]

>>> seq = '123456789'
>>> slice(None,None,1).indices(len(seq)) #[::1] 
(0, 9, 1)
>>> seq[::1]
'123456789'

>>> slice(None,None,-1).indices(len(seq)) #[::-1] 
(8, -1, -1)
>>> seq[::-1]
'987654321'

With this knowledge the rules are simple.
start and stop values will always be the same for posetive step values(default is step=1)
start and stop values will always be the same for negative step values.

We can test that this is True.

#Posetiv step 
>>> seq[::4]
'159'
>>> slice(None,None,4).indices(len(seq)) 
(0, 9, 4)

#Negative step 
>>> seq[::-4]
'951'
>>> slice(None,None,-4).indices(len(seq)) 
(8, -1, -4)

Edited by snippsat

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.