Here is the way that I do this when I want copy vs reference for lists. >>> a = [1,2] >>> b = a[:] >>> b[0] = a[0] + b[0] >>> b [2, 2] >>> a [1, 2] >>>
the a[:] does a copy of the list while a=b creates a reference. It is a little hard to get used to at first. On Apr 19, 2:50 pm, wb <[email protected]> wrote: > coming from C I'm confused about this behavior in assignment: > > 1) using only integers ---------------------------------- > sage: a=2 > sage: b=2 > sage: b=b+a > sage: b > 4 > sage: a > 2 > > so (at least), after b=b+a, 'b' seems to have gotten its own instance, > however > > 2) using lists ---------------------------------------------------- > sage: a=[1,2] > sage: b=a > sage: b[0]=b[0]+a[0] > sage: b > [2, 2] > sage: a > [2, 2] <------- ?!? > > (which results also if done directly in python). So, after > b[0]=b[0]+a[0], 'b' does not seem to get its own instance and 'a' > therefore also gets modified ..!? ... which somehow seems > inconsistent with 1) and very strange anyway ... > > Finally > > 3) ------------------------------------------------- > sage: a=[1,2] > sage: b=a+[] <------------ ! Trying to force (maybe?) an own > instance for 'b' > sage: b[0]=b[0]+a[0] > sage: b > [2, 2] > sage: a > [1, 2] <------------ ok > > in exmpl. 3) the list behaves similar to the integers in exmpl. 1). > > Question: is the assignment b=a+[] the only way to achieve this ? > > Thanks, > wb > > -- > 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 > athttp://groups.google.com/group/sage-support > URL:http://www.sagemath.org -- 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 URL: http://www.sagemath.org
