This is an aliasing problem. Change the code to

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

regards,
Sarma.

On Tue, Apr 18, 2017 at 2:16 AM, Mats Wichmann <m...@wichmann.us> wrote:

> 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])
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to