118

I'm trying to understand the following piece of code:

# node list
n = []
for i in xrange(1, numnodes + 1):
    tmp = session.newobject();
    n.append(tmp)
link(n[0], n[-1])

Specifically, I don't understand what the index -1 refers to. If the index 0 refers to the first element, then what does -1 refer to?

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Dawood
  • 5,106
  • 4
  • 23
  • 27
  • 2
    I think this question covers the same ground in the end as [Good Primer for Python Slice Notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) – Daenyth Jul 06 '12 at 18:43

2 Answers2

216

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

Toomai
  • 3,974
  • 1
  • 20
  • 22
  • 21
    However, there is a caveat: the behavior is slightly different if you try slice notation. If you use -1 in that case, it returns one element from the last. >>> a = [1,2,3,4,5] >>> a[-1] 5 >>> a[:-1] [1, 2, 3, 4] – abought Jul 06 '12 at 20:18
  • 10
    @abought Isn't that normal behavior though? If I said `a[4]`, it would return 5, but `a[:4]` returns [1,2,3,4] – yesennes May 18 '17 at 13:34
  • 4
    @abought That is solely because slice notation *excludes* the element with the index specified after the colon! `-1` still refers to the last value in the list. – xuiqzy May 28 '20 at 11:47
  • Python's negative index convention makes it more hard to find off-by-one bugs. – Youjun Hu Jul 11 '22 at 07:00
17

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.

Russell Borogove
  • 18,516
  • 4
  • 43
  • 50
  • 2
    True although not all languages are able to follow this design. In C, `n[-1]` literally means the element prior to `n[0]` and is fine if n points into an array - even if it's more normally a bug. [http://dlang.org/d-array-article.html](Slicing in D) is an interesting take on memory-safe slicing in a native language including from-right notation. – John McFarlane Sep 11 '14 at 18:15
  • 1
    Python got this feature directly from Perl: https://stackoverflow.com/questions/15911115/arrays-and-negative-indexes-in-perl . To my knowledge Larry came up with it himself for Perl, but he might have gotten it from somewhere else. – Ken Williams Aug 30 '17 at 20:07