I noticed that something weird happens when I use a recursion inside a list comprehension. If the recursion goes too deep the interpreter seemingly goes idle (I waited for 5 minutes and nothing happened).
For the sake of this question assume that I want to flatten nested lists (I don't - but it's a short code sample that illustrates the problem I am experiencing):
def flatten(x):
if isinstance(x, list):
return [a for i in x for a in flatten(i)]
else:
return [x]
With a helper function to create a nested list:
def wrap_in_lists(value, depth):
a = value
for _ in range(depth):
a = [a]
return a
It works great when using:
>>> flatten(wrap_in_lists(1, 2**10))
[1]
But it completely stops when I use:
>>> flatten(wrap_in_lists(1, 2**11))
# Nothing happens, no exception, no result, no segfault, ...
My question is: What happens/happened here? Why is there no response at all?
What is odd is that a similar approach using a generator doesn't show this behavior:
def flatten(l):
def inner(x):
for item in x:
if isinstance(item, list):
yield from inner(item)
else:
yield item
return list(inner(l))
>>> flatten(wrap_in_lists(1, 2**11))
[1]
>>> # although increasing the depth leads to an recursion error
>>> flatten(wrap_in_lists(1, 2**12))
RecursionError: maximum recursion depth exceeded
If it's important I'm using Python 64bit 3.6.6 on Windows in a jupyter lab.