2
my_list = range(1,11)
print my_list[10:0:-1]

This code prints [10, 9, 8, 7, 6, 5, 4, 3, 2] which does not make sense. Why does it do this?

user2108462
  • 855
  • 7
  • 23

2 Answers2

2

Because the second element in a slice is exclusive. The indices run from 10 until 1, not until 0.

To reverse my_list, just omit the start and end:

print my_list[::-1]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

It's just the way the notation works. As @GregHewgill put very well:

The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference between end and start is the number of elements selected (if step is 1, the default).

This will select all elements, in reverse order, starting with the element at index 10, and going until the element at index 0 (but not including that element).

Another way is to think of the notation as shorthand for a traditional for loop over the indices. In this case:

for(int i=10; i>0; i-=1)
Community
  • 1
  • 1
lc.
  • 113,939
  • 20
  • 158
  • 187