# [Sage vs Python] Matrix indexing and list standards

Hello, Sage Community!

Since I learned Sage, I have used the notation A[i][j] (which obviously came from my previous experience with Python lists) to access the (i+1, j+1)-th element of a matrix. However, I discovered a few weeks ago that I can also use the syntax A[i,j]. I am wondering which of these two ways of matrix indexing is preferred in Sage?

My tests using timeit indicate that the second syntax is faster than the first one by a factor of 500. So I suppose it to be simply natural that the fastest syntax is preferred. However, why to deviate from the list syntax? After all, lists and lists of lists are (in some sense) arrays, too.

On the other hand, talking about lists, there is the syntax [1..10], which creates the list

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Why is this the case when Python would ignore the 10? For example, range(1, 10) is equivalent to

[1, 2, 3, 4, 5, 6, 7, 8, 9]


Even srange(1, 10) creates the same list, but with Sage Integers, instead of Python's ints. Is there any good reason for having [1..10]be equivalent to srange(1, 11)?

edit retag close merge delete

Sort by » oldest newest most voted

I would expect A[i][j] to be slower because it first has to create the vector A[i] and then extract an element from it, whereas A[i,j] does a single extraction without creating intermediate objects. There is overhead in constructing a mathematical object like a vector. Also, A[i,j] calls a single method, A.__getitem__, whereas A[i][j] performs two calls: it calls A.__getitem__ once to form the vector v = A[i], and then calls v.__getitem__ on that vector.

So if you care about performance, use A[i,j]. If you need the intermediate vector, use A[i].

Regarding the ellipsis notation, it's written for mathematicians, like a lot of Sage. In mathematical writing, "1, 2, ..., 10" includes 10. range is not a standard thing for mathematicians, so there was no reason to change Python's behavior, and srange is the Sage version of that, so again, no reason to deviate from Python. But mathematicians will expect [2, 4, .., 10] to include 10.

more

Hello, @john-palmieri. Thank you very much for answering my question. Unfortunately, I have updated it to include another inconsistency between Sage and Python. I hope you can help me with that too, so I can tick your answer as correct.

( 2019-11-18 23:46:56 +0200 )edit
3

These are really two separate questions, aren't they?

( 2019-11-18 23:55:09 +0200 )edit

Yeah, sorry. I am exhausted by so much work, that I didn't organize my ideas correctly. Thank you very much for answering.

Should I separate them?

I am a mathematician, but I never used the ellipsis in the context of programming. Happy to learn something new.

( 2019-11-19 00:18:47 +0200 )edit