I have tried to implement a flatten function to even flatten strings but got an error for Recursion. Could someone help resolve this puzzle?
def flatten(items):
for x in items:
if isinstance(x, Iterable):
yield from flatten(x)
else:
yield x
items = [2, [3, 4, [5, 6], 7], 8, 'abc']
for x in flatten(items):
print(x)
I was expecting to print '2, 3, 4, 5, 6, 7, 8, a, b, c'; but instead, I got '2, 3, 4, 5, 6, 7, 8 and a RecursionError. I think the 'abc' is also 'Iterable', so why the code doesn't work?
Thank you!
source https://stackoverflow.com/questions/74633320/recursionerror-in-a-for-loop
Comments
Post a Comment