Negative Slicing in Python

In this code, -1 index is 3, and -2 index is 2, right? But since we don’t include the second index itself, then we only have one value which is 3. However, why is the result an empty list?

nums = [1,2,3]
vals = nums [-1:-2]
print (vals)

Thank you in advance.

The problem is that Python doesn’t switch the direction of iteration - the step is still +1. Your slice means to start at index -1 (aka len()-1=2), and then add 1 until the index is >= -2. Which is true immediately, so the result is empty. If you use a negative step to go the other direction, you get the result you expect - nums[-1:-2:-1]. (To clarify the 3rd value is the step.)

3 Likes

Thanks bro you helped a lot!

1 Like

Thank you for this! I think I will need to look up for more examples to check if I understood. Thank you!