0

I want to get the last 5 elements of a list, but there is no guarantee that the list is at least 5 elements long. I could add a manual check and such, but it seems like I don't have to (the code appears to be working well) when using negative indexing.

Just wanted to make sure I don't get any unexpected behavior/memory leaks, since the code seems to work just fine, and I can't find much documentation on using negative indexing past the usual -1 or -2 cases.

Example of what I mean:

mylist = [2, 3, 4]
print(mylist[-5:])
Output:
[2, 3, 4]
Eli.helpmepls
  • 11
  • 1
  • 4
  • 1
    The same with positive indexing like `[0:5]`: if you want 5 elements but there are only three, well, then you get only three. – deceze Jun 30 '23 at 09:23
  • negative indexing which starts counting from the last element to the first in your case the start point of the slicing is -5 and the output should be the list of at index -5, -4, -3, -2, and -1. But you don't have elements at index -4 and -5, so it just print the last 3 elements starting from at index -5 – Dejene T. Jun 30 '23 at 09:28

0 Answers0