Below is my code to flatten a python list. I've tried to use the concept of recursion to do the same. The inputs are either of integers, strings or lists. What I'm struggling with is I'm unable to follow as to why is my return giving me a list with repeated values? How do I rectify the same?
copyList = []
def flatten(aList):
for char in aList:
if isinstance(char,int) or isinstance(char,str):
copyList.append(char)
else:
char_pos = aList.index(char) + 1
return flatten(char) + flatten(aList[char_pos:len(aList)])
print copyList
return copyList
My output is correct in terms of getting the right output but the return seems to be giving me the list repeated several times. Unable to understand what went wrong!!
Sample output here: flatten([1,'a',2,[['alpha']],3,4])
[1, 'a', 2, 'alpha'] [1, 'a', 2, 'alpha'] [1, 'a', 2, 'alpha', 3, 4]
Out[2]: [1, 'a', 2, 'alpha', 1, 'a', 2, 'alpha', 1, 'a', 2, 'alpha', 3, 4]