Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative list index? [duplicate]

Tags:

python

list

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?

like image 536
Dawood Avatar asked Jul 06 '12 18:07

Dawood


People also ask

What does negative index in a list indicate?

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.

What is negative index in list Python?

Negative indexing in Python means the indexing starts from the end of the iterable. The last element is at index -1, the second last at -2, and so on.

Can you have negative array index?

JavaScript arrays are collections of items, where each item is accessible through an index. These indexes are non-negative integers, and accessing a negative index will just return undefined . Fortunately, using Proxies, we can support accessing our array items starting from the end using negative indexes.

Does Python allow negative indexing?

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.


2 Answers

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.

like image 181
Toomai Avatar answered Oct 25 '22 17:10

Toomai


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.

like image 27
Russell Borogove Avatar answered Oct 25 '22 19:10

Russell Borogove