Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python recursive function is not using argument correctly

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading