[Tutor] reg. list update

Mats Wichmann mats at wichmann.us
Mon Apr 17 16:46:32 EDT 2017


On 04/17/2017 12:41 PM, Rasika Sapate via Tutor wrote:
> Dear Python group,
> I had written following code.
> 
> super = []
> sub = [""]*3
> other = ["a","b","c","d"]
> sub[0] = "hi"
> sub[1] = "hello"
> for item in other:
>     sub[2] = item
>     super.append(sub)
> for item in super:
>     print item
> 
> 
> Output :
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> ['hi', 'hello', 'd']
> 
> 
> Expected output:
> ['hi', 'hello', 'a]
> ['hi', 'hello', 'b']
> ['hi', 'hello', 'c']
> ['hi', 'hello', 'd']
> 
> 
> Is there anything wrong in this code or any feature of python?

yeah, feature of Python.  you could google for "deep copy".

in short, sub[2] ends up with a reference to, not a copy of, the object
referenced by "item" in the first for loop. all four lists hold this
reference. by the time you go to print, that's a reference to the value
"item" held when the first loop exited, or 'd'.  item itself no longer
refers to that, you assign new things to it.

You can see this by adding a couple of debug print lines

super = []
sub = [""]*3
other = ["a","b","c","d"]
sub[0] = "hi"
sub[1] = "hello"
for item in other:
    sub[2] = item
    print "item id:", id(item)
    super.append(sub)
for item in super:
    print item
    print "item[2] id:", id(item[2])


More information about the Tutor mailing list