Just can not wrap my head why this code would not work:
def list_flatten(a_list):
for item in a_list:
if isinstance(item, list):
list_flatten(item)
else:
yield item
print(list(list_flatten([["A"]])))
print(list(list_flatten(["A", ["B"], "C"])))
Expecting:
- ["A"] and
- ["A", "B", "C"]
Getting
- [] and
- ["A", "C"]
Side note: Do not want to use chain.from_iterable, because it will breakdown the strings too, like ["123"] might end up ["1","2","3"]
CodePudding user response:
You're not doing anything with the result of your recursive call.
Change
list_flatten(item)
to
yield from list_flatten(item)
and you should be good to go. (See the docs for yield from
.)