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.
Did you like this article?
If you liked this article, consider subscribing to this site. Subscribing is free.
Why subscribe? Here are three reasons:
- You will get every new article as an email in your inbox, so you never miss an article
- You will be able to comment on all the posts, ask questions, etc
- Once in a while, I will be posting conference talk slides, longer form articles (such as this one), and other content as subscriber-only