0

I have a code as below and I need it to unpack lists using yield:

def flat_list(array):
    d=[]
    for i in array:
        if not isinstance(i, list):
            yield i
        else:
            flat_list(i)

For example, flat_list([1, [2, 2, 2], 4]) should return [1, 2, 2, 2, 4]. My code returns [1, 4].

I understand from previous question that I need not only recursively call a function, but to specify what it should do.

But how do you add flat_list(i) items to yield items? Something like flat_list(i).extend(yield i).

1
  • d is unused. You don't need to fill a list in your function when you yield Commented Oct 29, 2019 at 13:27

1 Answer 1

5

You should yield all of the items generated by the flat_list(i) call. You can do this with yield from.

def flat_list(array):
    for i in array:
        if not isinstance(i, list):
            yield i
        else:
            yield from flat_list(i)

for x in flat_list([1, [2, 2, 2], 4]):
    print(x)

Result:

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

2 Comments

What's d=[] for?
mistake, from old draft code

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.