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!
'abc'is a sequence that contains'a'as its first element, which is a sequence that contains'a'as its first element, which is a sequence that contains'a'as its first element... Basically, you have to special-case strings whenever you recursively explore any structure that might contain them.[2, 3, 4, 5, 6, 7, 8, 'abc']since "to flatten" means to remove nesting and one doesn't typically think of a list of strings as being a nested data structure.x = []; x.append(x)? Or worse,x = []; y = []; x.append(y); y.append(x)?