Negative list index?

PythonList

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDawoodView Question on Stackoverflow
Solution 1 - PythonToomaiView Answer on Stackoverflow
Solution 2 - PythonRussell BorogoveView Answer on Stackoverflow