Thursday, 3 August 2017

python - Negative list index?












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?


Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...