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

2
  • Does this answer your question? Why does my recursive function return None? Commented Mar 7, 2022 at 20:31
  • 2
    list_flatten(item) creates a new iterator (a generator), nothin is done with it and it is discarded Commented Mar 7, 2022 at 20:32

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.