# Bad index in a sublist

In the following code

A=[[99999,99999,1,99999],[1,99999,1,99999]]
A[0].index(A[0][2])
A[0].index(A[0][0])
A[0].index(A[0][1])


The index returned is the true one if the value is encountered form the first time in the 0th element of A. So A[0].index(A[0][2]) and A[0].index(A[0][0]) give the good index. But not A[0].index(A[0][1]). Why ?

edit retag close merge delete

Sort by ยป oldest newest most voted

First, your question adds a useless level of complexity, since everything happens within A[0], so let me first reduce it:

sage: B = [9, 9, 1, 9]
sage: B.index(B[0])
0
sage: B.index(B[1])
0
sage: B.index(B[2])
2
sage: B.index(B[3])
0


You can check the documentation of the index method of lists as follows:

sage: B.index?


As you can see, this method B.index(x) returns the smallest index i such that B[i]=x (when it exists, otherwise it raises a ValueError).

In our case, there are three indices i for which B[i] equals 9, namely 0, 1, 3. The smallest of them is 0, hence B.index(9) will return 0. The fact that 9 was provided by B[0], B[1] or B[3] does not matter.

Note that this question is only about the Python language, not Sage. Hence you might find tons of explanations about this on the web.

more

Sorry to both. As I am not a professional in programming some times, I lose control.

( 2021-03-22 12:15:36 +0200 )edit