On Thursday, November 12, 2015 at 6:09:26 PM UTC-8, Roberto La Scala wrote:

> It happens that the value of the list l changes for different values of i.
>
> Since you are not saying what answer you expected, it is difficult to 
judge in what sense the answer seemed strange to you. However, the 
following is sometimes considered surprising in python:

sage: a=[1]
sage: b=[a,a]
sage: b
[[1], [1]]
sage: b[1].append(2)
sage: b
[[1, 2], [1, 2]]

As you can see, b is a list consisting of *the same* list a. Hence, a 
change to "a" in one place affects all occurrences.

Whenever you *mutate* a list, you have to ask yourself if you are free to 
do so or if someone else might be holding a reference to the same list and 
therefore will be affected by the change too.

One solution here would be to *replace* b[1] by a new list rather than 
append an element to b[1].

sage: a=[1]
sage: b=[a,a]
sage: b[1]= a + [2]
sage: b
[[1], [1, 2]]

 

-- 
You received this message because you are subscribed to the Google Groups 
"sage-support" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sage-support.
For more options, visit https://groups.google.com/d/optout.

Reply via email to