[Tutor] lists, name semantics

Cameron Simpson cs at zip.com.au
Sun Apr 19 06:08:06 CEST 2015


On 18Apr2015 22:03, Bill Allen <wallenpb at gmail.com> wrote:
>On Apr 18, 2015 4:11 PM, "boB Stepp" <robertvstepp at gmail.com> wrote:
>> On Sat, Apr 18, 2015 at 3:28 PM, Bill Allen <wallenpb at gmail.com> wrote:
>> > On Apr 18, 2015 7:50 AM, "Peter Otten" <__peter__ at web.de> wrote:
>> >> You can test your newfound knowledge by predicting the output of the
>> >> following script:
>> >>
>> >> a = [1, ["x", "y"], 3]
>> >> b = a[:]
>> >>
>> >> a[1][1] = "hello!"
>> >>
>> >> print(a) # [1, ['x', 'hello!'], 3]
>> >> print(b) # what will that print?
>> >>
>> >> Think twice before you answer. What is copied, what is referenced?
>>
>> > print(b) will print the original copy of a which b now references which
>is
>> > [1, ["x", "y"], 3]
>>
>> Uh, oh! You should have checked your work in the interpreter before
>> replying! Peter is being very tricky!! (At least for me...) Look again
>> at that list inside of a list and... [...]
>
>Ok, just tried it out.  In this example b=a and b=a[:] seem to yield the
>same results even after the change to a, which I do not understand.  Should
>not b be a copy of a and not reflect the change?

Because is it a _shallow_ copy. Doing this:

  b = a[:]

produces a new list, referenced by "b", with the _same_ references in it as 
"a". a[1] is a reference to this list:

  ["x", "y"]

b[1] is a reference to the _same_ list. So "a[:]" makes what is called a 
"shallow" copy, a new list with references to the same deeper structure.

So this:

  a[1][1] = "hello!"

affects the original x-y list, and both "a" and "b" reference it, so printing 
either shows the change.

By contrast, this:

  a[1] = ["x", "hello"]

_replaces_ the reference in "a" with a reference to a new, different, list.

Sometimes you want a "deep" copy, where "b" would have got a copy of the 
iriginal x-y list. See the "copy" module's "deepcopy" function, which supplies 
this for when it is needed:

  https://docs.python.org/3/library/copy.html#copy.deepcopy

Cheers,
Cameron Simpson <cs at zip.com.au>

Draw little boxes with arrows.  It helps.       - Michael J. Eager


More information about the Tutor mailing list