Steven D'Aprano wrote: > But slices are slightly different. When you provide two indexes in a > slice, they mark the gaps BETWEEN items:
The other explanation that Python uses half-open intervals works for me. > Now, what happens with *negative* indexes? > > mylist = [ 100, 200, 300, 400, 500 ] > indexes: ^ ^ ^ ^ ^ ^ > -6 -5 -4 -3 -2 -1 > > mylist[-5:-2] will be [200, 300, 400]. Easy. >>> mylist = [ 100, 200, 300, 400, 500 ] >>> mylist[-5:-2] [100, 200, 300] Off by one, you picked the wrong gaps. Slightly related is a problem that comes up in practice; you cannot specify "including the last item" with negative indices: >>> for i in reversed(range(len(mylist))): ... print(mylist[:-i]) ... [100] [100, 200] [100, 200, 300] [100, 200, 300, 400] [] A simple fix is >>> for i in reversed(range(len(mylist))): ... print(mylist[:-i or None]) ... [100] [100, 200] [100, 200, 300] [100, 200, 300, 400] [100, 200, 300, 400, 500] The hard part is to remember to test whenever a negative index is calculated. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor