brain stuck. whats occurring here?

mensanator at aol.com mensanator at aol.com
Thu Feb 7 19:01:12 EST 2008


On Feb 7, 3:13 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote:
> En Thu, 07 Feb 2008 16:16:11 -0200, mensana... at aol.com  
> <mensana... at aol.com> escribió:
>
> > On Feb 7, 11:38 am, Matthew_WAR... at bnpparibas.com wrote:
> > I don't see why you should get either.
>
> > Especially considering this behaviour:
>
> >>>> a=[]
> >>>> row=[ [] for n in range(0,10) ]
> >>>> a.extend(row[:])
> >>>> a
> > [[], [], [], [], [], [], [], [], [], []]
> >>>> a[0].extend(row[:])
> >>>> a
> > [[[...], [], [], [], [], [], [], [], [], []], [], [], [], [], [], [],
> > [], [], []]
>
> Those [...] should give a clue. Usually Python doesn't "shorten" a list  
> representation: if it takes a thousand lines to output a list, there will  
> be a thousand lines of output. The [...] means that the list is  
> *recursive*: it has an element that refers to the list itself, so it can't  
> be represented in the normal way.
> Why is it recursive? row[:] is a new list, not the same object as row. It  
> is a copy - but a "shallow" copy, because their elements aren't copies  
> themselves. So row[0] is the same object as row[:][0]
>
> >>> x = row[:]
> >>> x == row
> True
> >>> x is row
> False
> >>> x[0] is row[0]
>
> True
>
> In the line a[0].extend(row[:]), a[0] is THE SAME LIST as row[:][0], the  
> first item you are appending. That is, the first thing extend() does is  
> conceptually a[0].append(a[0]) - and you got a recursive structure.

I thought that it was some kind of recursive hocus pocus.
That explains why no matter how many indexes I ask for,
I always get the same result.

>>> a[0][0][0][0][0][0][0][0][0][0][0][0][0][0]
[[...], [], [], [], [], [], [], [], [], []]

>
> > Bug in IDLE?
>
> No, just a misunderstanding of what [:] does, I presume.

You didn't answer my question, but I just realize that I
mis-typed my example, so never mind.

>
> --
> Gabriel Genellina




More information about the Python-list mailing list