Velocity Reviews > nested lists - utter newbie

nested lists - utter newbie

rahoool@gmail.com
Guest
Posts: n/a

 07-01-2005
Hi,
why is this possible -
>>>b = [1,2,3]
>>>b[2] = b
>>>b

[1,2,[...]]
>>>b[2]

[1,2,[...]]
>>>b[2][2][2][2][2]

[1,2,[...]]

but this is not -
>>>x = [1,2,x]

Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'x' is not defined

thanks
r_a_h_o_o_l

Benjamin Niemann
Guest
Posts: n/a

 07-01-2005
http://www.velocityreviews.com/forums/(E-Mail Removed) wrote:

> Hi,
> why is this possible -
>>>>b = [1,2,3]
>>>>b[2] = b
>>>>b

> [1,2,[...]]
>>>>b[2]

> [1,2,[...]]
>>>>b[2][2][2][2][2]

> [1,2,[...]]
>
> but this is not -
>>>>x = [1,2,x]

> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> NameError: name 'x' is not defined

Because the right hand side ('[1,2,x]') is evaluated *before* the value is
bound to the name 'x' - and at this point there is obviously no name 'x'
defined.

--
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/

Terry Hancock
Guest
Posts: n/a

 07-01-2005
On Friday 01 July 2005 05:37 am, Benjamin Niemann wrote:
> (E-Mail Removed) wrote:
>
> > Hi,
> > why is this possible -
> >>>>b = [1,2,3]
> >>>>b[2] = b
> >>>>b

> > [1,2,[...]]
> >>>>b[2]

> > [1,2,[...]]
> >>>>b[2][2][2][2][2]

> > [1,2,[...]]
> >
> > but this is not -
> >>>>x = [1,2,x]

> > Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> > NameError: name 'x' is not defined

>
> Because the right hand side ('[1,2,x]') is evaluated *before* the value is
> bound to the name 'x' - and at this point there is obviously no name 'x'
> defined.

OTOH, the name "b" was bound to the list, so it can be put into
the list, just like any other name. At that point, the list contains
a series of references, one of which happens to be to itself.

If you are familiar with Unix/Linux filesystems, you've probably
already seen behavior like this with either symbolic or hard links --
it's quite possible to create loops so that a directory is contained
within itself. Such a structure is not strictly a "tree" any more,
but a "directed graph". Those are the data structures terms for

The *really* smart thing is that Python *writes* the list as:

[1,2,[...]]

instead of printing a traceback due to "excessive recursion" which
is what it used to do. This is because the representation method
was changed to catch such circular references and stick in the "[...]"

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks http://www.anansispaceworks.com