0

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?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

12 Comments

Thanks for the response but I still don't get why list2 in list1 does not result in error.
Okay if I give you list1=[list2,list1] and you search for list2 in it, you find it immediately. It never tries to see if it is in list1 (as in list1[1] - the second thing) @user3218450
Going by that reasoning list1 in list1 should not result in error right? since list1[1] is list1
You can get the recursion limit: sys.getrecursionlimit(). You can change the max by running sys.setrecursionlimit(). My default recursion limit is 1000, but it may be machine specific.
@user3218450 what do you expect to happen, if I asked you to define "x in y" for a list y what would you do, say "check if list itself is x" or "for each one of the things in y see if x is in it".
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.