One of the most common ways of finding the first element in a list in Python is using the index 0.
I was recently thinking of coming up with a more creative idea and I figured out another way.
It’s not something that you may have not figured out yourself. It also doesn’t mean that someone doesn’t know it.
Still, there is always someone who may also find it helpful or that hasn’t had the chance to have time to think about it.
Here how it goes…
You probably know about negative indexes that you may be using regularly, for example, you can get the last element in an array using the index -1:
Now, if you keep on decreasing the negative index, you come up with elements that are closer to the beginning of the list.
This way, you can actually reach the end (i.e. the beginning):
You can generalize it a little bit more using len:
Note that I am not saying that you should use it, it was just entertaining for me to come up with it.
You should still use the index 0, as it is more readable for both you and for your fellow developers who are going to read your code.