The beauty of negative indexing

This might be one of the smallest, yet most beautiful features in Python: negative indexing. I'm still surprised why other languages haven't copied this feature because it such a simple feature, yet makes such a huge difference.

This might be one of the smallest, yet most beautiful features in Python: negative indexing. I'm still surprised why other languages haven't copied this feature because it such a simple feature, yet makes such a huge difference.

How many times have you wanted to get the last item in a list or the last character of a string? In most other languages you have to do something like this

numList.get(list.size() - 1)

Which doesn't seem too bad on its own, but you often do more with it. For example, to (immutably) drop the last item of an int list if it is a zero, you end up with this code, which is really ugly

if (numList.get(numList.size() - 1) == 0) {
  return numList.subList(0, numList.size() - 1)
}

The Python version with negative indexing is beautiful in comparison

if num_list[-1] == 0:
    return num_list[:-1]

If you are new to Python, or coming from another language, you might not have used negative indexing before. Simply put, it allows you to index from the end of a data structure. For example to get the last element, you can do num_list[-1]. To get the second from last, you do num_list[-2] and so on, using negative numbers as the index to count from the end.

Comments

Sign in or become a Playful Python member to join the conversation.
Just enter your email below to get a log in link.