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?

0

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

Comments

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)

3 Comments

@user2108462 What do you mean?
Why do the forward indices run from 0 to 10 but the backward indices only go from 10 to 1?
@user2108462: forward it runs from 0 to 9 if you use [0:10].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.