How does negative indexing work in python?
Just a quick refresh of a python programming concept
Friendly reminder regarding python slice notation for negative indexing. It's covered really well here.
Basically, the last value has an index of -1... second last has an index of -2... and so on.
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
Sample code:
animal_list = ["lion", "wolf", "tiger", "panther"]
print(animal_list[-1]) # Last element in sequence
print(animal_list[-2]) # Second last element in sequence
print(animal_list[-3:]) # Last 3 elements in sequence
print(animal_list[-3:-1])
Sample Output:
panther
tiger
['wolf', 'tiger', 'panther']
['wolf', 'tiger']