nested lists - utter newbie

B

Benjamin Niemann

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 -
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.
 
T

Terry Hancock

Hi,
why is this possible -
b = [1,2,3]
b[2] = b
b [1,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
them, and you might try a little googling to learn more about them.

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 "[...]"
instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top