In the following code, I have run into a RecursionError: maximum recursion depth exceeded.
def unpack(given):
for i in given:
if hasattr(i, '__iter__'):
yield from unpack(i)
else:
yield i
some_list = ['a', ['b', 'c'], 'd']
unpacked = list(unpack(some_list))
This works fine if I use some_list = [1, [2, [3]]], but not when I try it with strings.
I suspect my lack of knowledge in python. Any guidance appreciated.
for x in 'a'yields'a'itself.some_list = []; some_list.append(some_list); unpacked = list(unpack(some_list))to see that this can happen with anything with depth>1000. So the remaining question is why every string has depth>1000, which wim's answer (and BallpointBen's comment) explains.__iter__forlistreturns itself, and naturally it's unending recursion?some_list[0] is some_list. I thought this would be less surprising than the fact that ifs = 'a',s[0] is s, so it would help illuminate the problem, but now that I think about it, how many people actually know about recursive lists in Python? The only really obvious example would be a class that explicitly iterates itself, which is too big and distracting to be worth commenting about; better to just go straight tos[0] is sfor strings as BallpointBen did.