# To give a name to an append list

If I code this

A = matrix([[1/2, 1/4, 0], [1, 3, -1], [1, 1, 0]])
b = vector([5, 18,10])
c = vector([102, 303, -100])
t = matrix(A.augment(b))
c = c.list()
c.append(0)
show(t, c)


SageMath returns what is expected. But if I want to change the name of c.append(0)? It returns None, so I cannot reuse the augmented vector.

edit retag close merge delete

Sort by » oldest newest most voted

The method append modifies the list in place.

It does not return anything (or equivalently, it returns None).

It has the side-effect of modifying the list.

Doing d = c.append(0) assigns the result of c.append(0) (i.e., None) to d.

To get a new list consisting of the former value of c with one extra element 0, use:

sage: d = c + 


Recommended: go through a few of SageMath's thematic tutorials, especially those in the section "Introduction to Python".

In a comment after my initial answer, there is a follow up question about Python equivalents of some Mathematica functions for operating on lists: RotateLeft, RotateRight, PadLeft, PadRight (the links point to the Wolfram language reference manual entries for those functions).

Implementing their equivalent in Sage is a good exercise after going through the tutorial.

One could make two versions, one that rotates or pads inplace, one that returns the result.

Here is one way to rotate right one step, inplace:

sage: a = [0, 3, 9, 5, 6, 8, 4]
sage: a[:0] = [a.pop()]
sage: a
[4, 0, 3, 9, 5, 6, 8]


Here is a rotated_right function:

def rotated_right(a, n=1):
if len(a) < 2 or n % len(a) == 0:
return a[:]
n = n % len(a)
return a[-n:] + a[:-n]


A pad_right function and a padded_right function:

def pad_right(a, n=1)
if len(a) < n:
a.extend( * (n - len(a)))

if len(a) < n:
return a[:] +  * (n - len(a))
return a[:]


Further recommendations:

more

Ok my question was stupid, but I wonder if there is some implementation of mathematica RotateLeftRotateRightPadLeft, PadRight.... which are very usefull functions.

1

Writing such functions would be an excellent exercise for learning Python's basic list management... I second slelievre's recommendation, and remind you of a previous recommendation about this book...

I second @Emmanuel Charpentier's recommendation to read "Calcul mathématique avec Sage". I learned a lot from it.

You are both particularly right. But, notice there is always a but, I have a huge lot of courses and I postpone always to learn Python seriously, because of a lack of time.