From: Joan Miller on 5 Mar 2010 13:01 What does a slice as [N::-1] ? It looks that in the first it reverses the slice and then it shows only N items, right? Could you add an example to get the same result without use `::` to see it more clear? Thanks in advance From: Arnaud Delobelle on 5 Mar 2010 13:12 Joan Miller writes: > What does a slice as [N::-1] ? > > It looks that in the first it reverses the slice and then it shows > only N items, right? > > Could you add an example to get the same result without use `::` to > see it more clear? > > Thanks in advance >>> l = range(10) >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> l[7::-1] [7, 6, 5, 4, 3, 2, 1, 0]>>> [l[i] for i in range(7, -1, -1)] [7, 6, 5, 4, 3, 2, 1, 0] -- Arnaud From: Steven D'Aprano on 5 Mar 2010 13:22 On Fri, 05 Mar 2010 10:01:40 -0800, Joan Miller wrote: > What does a slice as [N::-1] ? Why don't you try it? >>> s = "abcdefgh" >>> s[4::-1] 'edcba' The rules for extended slicing are not explained very well in the docs, and can be confusing. In my experience, apart from [::-1] it is best to always use a positive stride (the third number). -- Steven From: Steven D'Aprano on 5 Mar 2010 13:28 On Fri, 05 Mar 2010 18:12:05 +0000, Arnaud Delobelle wrote: >>>> l = range(10) >>>> l > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> l[7::-1] > [7, 6, 5, 4, 3, 2, 1, 0] >>>> [l[i] for i in range(7, -1, -1)] > [7, 6, 5, 4, 3, 2, 1, 0] Where does the first -1 come from? Slices are supposed to have default values of 0 and len(seq): >>> l[7::1] [7, 8, 9]>>> [l[i] for i in range(7, len(l), 1)] [7, 8, 9]>>> [l[i] for i in range(7, len(l), -1)] [] I don't believe the actual behaviour is documented anywhere. -- Steven From: Mensanator on 5 Mar 2010 13:33 On Mar 5, 12:01 pm, Joan Miller wrote:> What does a slice as [N::-1] ? Starts at position N and returns all items to the start of the list in reverse order. > > It looks that in the first it reverses the slice and then it shows > only N items, right? Wrong. It shows N+1 items. Remember, counting starts from 0. > > Could you add an example to get the same result without use `::` to > see it more clear? for i in range(8,-1,-1):print(a[i],end=' ') although I doubt this is more clear. > > Thanks in advance  |  Next  |  Last