Can I detect an infinitely nested list?

Viewed 76

I've noticed an interesting property of Python objects, which is that they can be self-similar. For example, if you have a list and append itself to it, you'll get a list within a list within a list within a list...

x = []
x.append(x)
print(x)   # displayed as "[[...]]"

My question is, can you detect whether or not a list is infinitely nested? I tried x in x, but that's not foolproof -- the code below prints False when it should print True:

x = []
x.append(x)
y = [x, x]
print(y in y)

How can I solve this?

1 Answers

Sure. Write a function that iterates through the list, building a reference list of IDs found in the list. If any ID appears in one of its sub-lists, you have infinite nesting.

Maintain the list of "ancestor" IDs and recur on each element that's a list.

Can you do the coding now?

Related