Alex Becker - 1 year ago 57

Python Question

The extended slice syntax in python has been explained to me as "

`a[n:m:k] returns every kth element from n to m`

This gives me a good idea what to expect when k is positive. But I'm lost on how to interpret

`a[n:m:k]`

`a[::-1]`

`a[::-k]`

But how is this a generalization of the definition for k positive? I'd like to know how

`a[n:m:k]`

`"abcd"[-1:0:-1] = "dcb"`

Is

`a[n:m:-k]`

Answer Source

`[-1:0:-1]`

means : start from the index `len(string)-1`

and move up to `0`

(not included) and take a step of `-1`

(reverse)

So, the following indexes are fetched:

```
le -1, le-1-1, le-1-1-1 .... 1 # le is len(string)
```

example:

```
In [24]: strs='foobar'
In [25]: le=len(strs)
In [26]: strs[-1:0:-1] #the first -1 is equivalent to len(strs)-1
Out[26]: 'raboo'
In [27]: strs[le-1:0:-1]
Out[27]: 'raboo'
```