[Tutor] string reversal using [::-1]

Peter Otten __peter__ at web.de
Sun Jun 11 05:01:33 EDT 2017


Vikas YADAV wrote:

> Question: Why does "123"[::-1] result in "321"?
> 
>  
> 
> MY thinking is [::-1] is same as [0:3:-1], that the empty places defaults
> to start and end index of the string object.
> 
> So, if we start from 0 index and decrement index by 1 till we reach 3, how
> many index we should get? I think we should get infinite infinite number
> of indices (0,-1,-2,-3.).
> 
>  
> 
> This is my confusion.
> 
> I hope my question is clear.

It takes a slice object and a length to replace the missing aka None values 
with actual integers. You can experiment with this a bit in the interpreter:

>>> class A:
...     def __getitem__(self, index):
...         return index
... 
>>> a = A()
>>> a[::-1]
slice(None, None, -1)
>>> a[::-1].indices(10)
(9, -1, -1)
>>> a[::-1].indices(5)
(4, -1, -1)
>>> a[::].indices(5)
(0, 5, 1)

So what a missing value actually means depends on the context.

Note that while I'm a long-time Python user I still smell danger when a 
negative step is involved. For everything but items[::-1] I prefer

reversed(items[start:stop])  # an iterator, not an object of type(items)

when possible.



More information about the Tutor mailing list