lists v. tuples

Duncan Booth duncan.booth at invalid.invalid
Wed Mar 19 10:56:31 CET 2008


castironpi at gmail.com wrote:

> I am puzzled by the failure on 'a in a' for a=[a].  >>> a== [a] also
> fails.  Can we assume/surmise/deduce/infer it's intentional?
> 
It may be less confusing if instead of an assignment following by a test 
you just consider doing the test at the same time as the assignment 
(then again it changes the behaviour so it may just be more confusing).

There is a very limited set of values for which you would expect this 
output:

>>> a==[a]
True
>>> a in [a]
True

The most obvious one is a simple recursive list:

>>> a = []
>>> a.append(a)
>>> a==[a]; a in [a]
True
True

Pushing the recursion down a level breaks some of the comparisons:

>>> a = [[]]
>>> a[0].append(a)
>>> a==[a]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: maximum recursion depth exceeded in cmp
>>> a in [a]
True
>>> a in a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: maximum recursion depth exceeded in cmp

which may be considered a bug or possibly it is just a limit of the 
implementation.

This also produces an overflow (in fact I think it is just the same 
situation as above, recursing on the same list is handled, recursing on 
different but equivalent lists is not):

>>> a = []; a.append(a)
>>> b = []; b.append(b)
>>> a==b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: maximum recursion depth exceeded in cmp




More information about the Python-list mailing list