newbie: comparing mutually recursive lists

Tim Peters tim_one at email.msn.com
Wed Sep 29 22:21:11 EDT 1999


[Andrew Hutcheson]
> If I create a pair of mutually recursive lists like
>
> 	a,b=[],[]
> 	a.append(b)
> 	b.append(a)
>
> and try to compare them I get a segmentation fault.

It's caused by a C stack overflow (unbounded recursion in the interpreter).

> I'm using the version of Python that comes with Debian 2.1 (Python 1.5.1
> (#1, Dec 17 1998, 20:58:15)  [GCC 2.7.2.3] on linux2 ).

All versions of Python suffer this.

> Does anyone know if this problem has been fixed?

Yes:  no <wink>.

> Failing that, can anyone suggest a workaround?

The easiest is-- honest --not to compare lists with cycles.  Note that
mutual recursion isn't necessary to provoke this; e.g.,

    a = []
    b = []
    a.append(a)
    b.append(b)

is just as bad.

Your other choice is to implement your own list comparison, that detects and
keeps track of cycles; see Lib/copy.py for the kind of machinery that's
needed.  This is expensive all the time, which is why the interpreter
doesn't do it.  If it's ever fixed in the language, it's more likely that
this kind of comparison will be declared illegal, and the implementation
will catch it with a much cheaper recursion counter (raising an exception if
the comparison recursion gets "too deep").  This wasn't done before because,
until recently, it was impossible for a comparison operator to raise an
exception (due to obscurities of the implementation).

if-real-lists-had-cycles-i'd-never-stop-shopping-ly y'rs  - tim






More information about the Python-list mailing list