Reputation: 55
So here is the construct
#list1 and list2
list1 = [(True,), (True,)]
list2 = [(True,), (True,)]
#Transformation
list1[0] = list2
list1[1] = list1
list2[0] = list1
list2[1] = list2
Which gives:
#Result
#list1 = [ list2 , list1 ]
#list2 = [ list1 , list2 ]
When I run this code
>>>list2 in list1
True
>>>list1 in list1
RuntimeError: maximum recursion depth exceeded in comparison
I believe the error occurs because getting the actual value of list1 for comparison results in an endless loop. However, list2 does not result in this error despite being constructed similarly.
So my question is, why is there a discrepancy in the error? Shouldn't "list2 in list1" cause an error too?
Upvotes: 0
Views: 990
Reputation: 5928
If you do
list = [1,2,3]
list.append(list)
it doesn't do this:
list.append([1,2,3])
That'd be creating a new list. It appends a "reference" to the list. This is because copying things that are not fundamental types is rarely what you want to do (PHP jab removed)
So say you do
list.append(4)
Now:
print(list[3][4])
will show 4, as the 3rd thing (4th really as they start at zero) is the list reference, we look at that's 4th (5th) which is the 4 we just appended. So
list is list[3]
Is true, they refer to the same actual lits.
The recursion happens for the same reason you can't do print(list)
, it starts looking, then it ends up looking in itself endlessly.
It ends because Python has a max stack depth, which is by default 500 I think, you can have a function call a function call a function ..... 497 more times. Yours will never terminate so hits this wall.
Upvotes: 3