My question is to create a function which iterates a list within a list, and have the code such that if I keep introducing another list within that list, it still iterates to return one list
e.g flatten_list([5, [4, 3, 2,[1,2,3]], 1])
gives [5,4,3,2,1,2,3,1]
My attempt at the question:
def flatten_list(x):
list1=[]
for i in x:
if type(i)==list:
for j in i:
list1.append(j)
else:
list1.append(i)
return list1
flatten_list([5, [4, 3, 2,[1,2,3]], 1])
But this gives an Output of:
[5, 4, 3, 2, [1, 2, 3], 1]
I'm quite new to coding and would appreciate a simple answer even if its quite long! I've looked at other stackoverflow questions similar to this however they use complex commands such as isinstance() or flatten() and they don't quite answer my specific question e.g. Iterate a list using recursion Recursively going through a list (python)