On Mar 21, 2009, at 1:31 AM, Rolandb wrote:

> Hi, I didn't expect that whole M would be effected.
>
> M=[[0..9]]*3
> print M[0]
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>
> M[1].remove(9)
> print M
> [[0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2,
> 3,
> 4, 5, 6, 7, 8]]

This is due to how Python behaves with references--it doesn't  
actually copy the entire list three times, it simply makes three  
references to the same original list. To see that they are actually  
the same underlying list

sage: M[0] is M[1]
True

To get three copies of the same thing, you can do

sage: M = [[0..9] for a in range(3)]
sage: M[1].remove(9)
sage: print M
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1,  
2, 3, 4, 5, 6, 7, 8, 9]]

Sage tries to avoid this pitfall by making most objects immutable.  
(An exception is vectors and matrices, where storage considerations  
make copying expensive, and even they can be made immutable.) There  
is talk about trying to implement copy-on-write semantics in some  
cases, but that's easier said than done.

- Robert


--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to