0

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"]

Laszlo
  • 302
  • 1
  • 10
  • Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – MisterMiyagi Mar 07 '22 at 20:31
  • 2
    `list_flatten(item)` creates a new iterator (a generator), nothin is done with it and it is discarded – juanpa.arrivillaga Mar 07 '22 at 20:32

1 Answers1

3

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.)

AKX
  • 152,115
  • 15
  • 115
  • 172