'Not able to flatten the list. need to understand how to flatten the list

I do not want to use any other built-in functions so just want to experiment the available list methods.

I am trying to flatten the list with the code below:

my_list = [1, 2, 3, 6, 4, [0, 8, 9]]
new_list = []
for num in my_list:
    new_list.extend([num])

print(new_list)

Expecting an output like this: [1, 2, 3, 6, 4, 0, 8, 9]
Getting the following output: [1, 2, 3, 6, 4, [0, 8, 9]]

The extend function is used to append all the elements of an iterable to the existing list. But the above code isn't working.



Solution 1:[1]

You have a mixed array so you need to check for that. So a function like

def flatlist(l):
    if l== []:
        return []
    elif type(l) is not list:
        return [l]
    else:
        return flatlist(l[0]) + flatlist(l[1:])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SpeedOfSpin