1

I'm using to his code to flatten nested tuples:

def get_tuple_leaves(t, out=[]):
    for i in t:
        if isinstance(i, str):
            yield i
        else:
            get_tuple_leaves(i, out)

The idea is to get an input such as (('a', 'b'), 'c') to turn to ('a', 'b', 'c')

But for some reason the recursive call never gets executed, and the output is ('c')

Jordan Valansi
  • 181
  • 2
  • 5
  • 1
    What is the purpose of your `out` variable? You're not doing anything with it. – pushkin Mar 01 '18 at 21:52
  • 1
    Also, assuming your default value for `out` is actually doing something, you should be careful with a mutable default argument if you don't understand it's semantics – juanpa.arrivillaga Mar 01 '18 at 21:53

1 Answers1

2

You're not returning, or rather, yielding from your recursive call. Try:

def get_tuple_leaves(t, out=[]):
    for i in t:
        if isinstance(i, str):
            yield i
        else:
            yield from get_tuple_leaves(i, out)

print(list(get_tuple_leaves((('a', 'b'), 'c'))))

which results in:

['a', 'b', 'c']