Ask Your Question
0

Bad index in a sublist

asked 2021-03-21 11:27:15 +0100

Cyrille gravatar image

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 flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-03-21 11:47:51 +0100

tmonteil gravatar image

updated 2021-03-21 16:28:20 +0100

slelievre gravatar image

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.

edit flag offensive delete link more

Comments

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

Cyrille gravatar imageCyrille ( 2021-03-22 12:15:36 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2021-03-21 11:27:15 +0100

Seen: 211 times

Last updated: Mar 21 '21