2

The following simple comparison of pure lists explodes on me:

a, b = [], []
for _ in range(1000):
    a, b = [a], [b]
a == b

Python 3.5.1:

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    a == b
RecursionError: maximum recursion depth exceeded in comparison

Python 2.7.11:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    a == b
RuntimeError: maximum recursion depth exceeded in cmp

Does the language/library offer a safe way to compare such deeply nested lists, or will I have to write my own iterative comparison code?

Edit: I'm asked to explain why my question isn't a duplicate of this. It isn't because that one is about infinite nesting and because I'm not asking for an explanation (I understand it already) but for whether Python offers a simple solution.

Community
  • 1
  • 1
Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107
  • 7
    You seriously have lists that are nested more than 1000 levels? That sounds like a problem in and of itself. – Falmarri Oct 24 '16 at 23:32
  • If this is a real situation, you know what recursion depth you'll need, and you're reasonably sure that your machine can handle such a depth, you can increase the maximum recursion depth. – TigerhawkT3 Oct 24 '16 at 23:40
  • @Falmarri No I don't actually have this, I just got curious when I noticed that the above doesn't work. But I don't see why a nested structure with 1000 or more levels would be a problem in general. – Stefan Pochmann Oct 24 '16 at 23:41
  • @TigerhawkT3 It's not a "real" situation for me, I'm just curious. Under a recent question about a recursive list-comparison function, someone commented that the professor shouldn't use that to teach recursion because it should be done iteratively. Then I tested the above and saw that Python itself also does it recursively. Didn't bother telling them that, but it inspired my above curiosity. – Stefan Pochmann Oct 25 '16 at 00:03
  • @StefanPochmann Interesting find. While checking this out in the shell for myself, it seems `__repr__` is implemented recursively too. – juanpa.arrivillaga Oct 25 '16 at 00:10

0 Answers0