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)
CodePudding user response:
Your code will work only for a list inside a list.
A better approach is using recursion for i
,
Something like this,
def flatten_list(x):
list1=[]
for i in x:
if type(i)==list:
for j in flatten_list(i):
list1.append(j)
else:
list1.append(i)
return list1
CodePudding user response:
This can be done using recursion without introducing flatten
or isinstance
:
def flatten_list(x):
output = []
for e in x:
if type(e) == list:
output.extend(flatten_list(e))
else:
output.append(e)
return output
===================================
print(flatten_list([5, [4, 3, 2,[1,2,3]], 1]))
[5, 4, 3, 2, 1, 2, 3, 1]
CodePudding user response:
def flatten_list(x, result = None):
tmp_result = []
if result :
tmp_result = result
for elt in x:
if type(elt) ==list:
flatten_list(elt, tmp_result)
else:
tmp_result.append(elt)
return tmp_result
print(flatten_list([5, [4, 3, 2,[1,2,3]], 1])) # Output : [5, 4, 3, 2, 1, 2, 3, 1]