Daniel Lemire's blog

, 1 min read

Python allows negative indexing on arrays!

Python supports indexes on arrays, and they work reasonably:

>>> [0,1,2][0]
0

[0,1,2][1]
1
[0,1,2][2]
2

Now, it gets strange when you use negative indexes…

>>> [0,1,2][-1]
2

[0,1,2][-2]
1

As it turns out, the same is true if you create an array in Python Numeric or Scipy: you can actually use negative indexes. Behold:

>>> from scipy import *

zeros(2)[-1]
0
array([0,1,2])[-1]
2

As it turns out, a[-x] is mapped to a[x%len(a)] or something like it. I cannot tell whether this is a bug or was meant to be that way. Any other language supports negative indexing? Why would you want this “feature”?

Update: Thanks to all my readers, I’m now aware that this is a standard and well documented feature of Python, special thanks to Toby and Will. Thanks to didier for pointing out that Perl supports them too.