Last time, we saw how to access list items using their index, like scores[0]
for the first item. Remember, indices start at 0.
Engagement Message
What if you wanted to get the very last item in a list, especially if you don't know how long the list is?
Python has a handy trick for this! You can use negative indices to count items from the end of the list backwards.
The index -1
always refers to the last item in the list.
Engagement Message
Does this seem like a useful shortcut?
So, if we have planets = ["Mercury", "Venus", "Earth"]
, using planets[-1]
would give you "Earth"
.
This works no matter how many items are in the list. -1
is always the last one.
Engagement Message
What would colors[-1]
give you if colors = ["red", "green", "blue"]
?
Following this pattern, -2
refers to the second-to-last item, -3
refers to the third-to-last item, and so on.
