[Tutor] Array slices in python with negative step
michaelsprayberry at gmail.com
Mon Jan 11 20:26:12 CET 2010
> > Hello All,
> > I am bit confuse how the slice works in case a negative step is
> > a = 'abcde'
> > a[::-1] gives me edcba
> > but [4:0:-1] gives me edcb
> > while searching net I came accross something which said the
> > If a negative stride is specified and the starting or stopping
> > omitted, they default to ``end of axis'' and ``beginning of axis''
> > respectively.
> > In my case 4 is end of axis and 0 is begining of the axis so a[::-1]
> > be equivalent to [4:0:-1] but result which I get in both the cases
> > validate.
> Your interpretation is wrong. In your case, 4 is start index, 0 is end
> index (as obviously shown by the result you get). Step -1 lets you
> backwards, but this does not change the fact that the end-index is the
> second argument of the slice, right? Now, python work with
> half-open intervals, meaning that the second border is excluded
> would return "abcd"). Which means in your case you won't get a in
Hope I'm clear... It can be a bit misleading at start but, as it's
> consistent, once you get used to it all works fine ;-)
Thanks for your response but I am still not clear; can you show me the
equivalent of [::-1] in terms actually specifying start-index,
which gives me reverse of the given arrary.
I hope this clears up your question.
a[begin index: end index: step]
a = ['a','b','c','d','e']
there are 5 indexes 0 through 4
a = ['e','d','c','b'] because you stopped at index 0 but did not include
a[::-1] uses the last index going back to and including index 0
as the following example shows
>>> a =[1,2,3,4,5,6]
>>> b = a[5:0:-1]
[6, 5, 4, 3, 2]
>>> b = a[5:-1:-1]
[1, 2, 3, 4, 5, 6]
>>> b = a[5::-1]
[6, 5, 4, 3, 2, 1]
Like I said I hope that clears it up a little
More information about the Tutor