2

I have the following code:

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

When I call flat_list([1, [2, 2, 2], 4]), I expect it to return unpacked list ([1, 2, 2, 2, 4]). Instead it returns ([1, 4]). Although, if I try (print i) instead of (d.append(i)), it returns unpacked i.

I read an article about recursion, it says return needs to be after base condition.

How do I use kindda (return d.append(i))?

0

1 Answer 1

2

you call your function, but don't do anything with its return value when calling it recursively

    else:
        d.extend(flat_list(i))

extend will take all the items from the list that flat_list returns, and adds them to your list you are creating within the function

Example

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

2 Comments

I have the same problem using yield. Could you, please, suggest a solution? def flat_list(array): for i in array: if not isinstance(i, list): yield i else: flat_list(i)
@KamalValikhanov - You should ask it as a new question with what you've tried and researched

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.