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]
''
>>> 
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.

because ir should be a[8:-1:-1]

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

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)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.