1

I have this piece of code:

a_list = [1,2,3,4,5,6]

print (a_list[::-1]) 
print (a_list[-1::-1])
print (a_list[5::-1])
print (a_list[-1:0:-1])

and the output is:

[6, 5, 4, 3, 2, 1]
[6, 5, 4, 3, 2, 1]
[6, 5, 4, 3, 2, 1]
[6, 5, 4, 3, 2]

Because step size is negative, the default start is at 5 or -1 index, so the first three statements give the same output. But when I was trying to figure out what the stopping point is I tried print (a_list[-1:0:-1]) and it obviously excludes the value at 0 index which is 1. also, the index before 0 is -1, and because it's the same as the starting point it gives an empty list. So my question is, what is the default stop point for a_list [ : :-1]? Or more generally, what is the default for any_list[start:stop:step] with a negative step size?

  • 3
    Please read about slices [here] (https://stackoverflow.com/questions/509211/understanding-slicing) – 555Russich Aug 08 '22 at 18:49
  • @555Russich thanks! I found my answer [here](https://stackoverflow.com/questions/509211/understanding-slicing#:~:text=What%20really%20annoys,at%2014%3A22) – YasamRashti Aug 08 '22 at 19:07

1 Answers1

0

When explicitly defined, the stop is excluded.

So in your first three example all remaining values are used, however in the last one (a_list[-1:0:-1]), 0 is excluded.

mozway
  • 194,879
  • 13
  • 39
  • 75