I am trying to use this code to flatten my list. By flatten I mean converting a list like
[1,[2], [[[[3]]]],4]
into
[1,2,3,4]
Here is my code
i = 0
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
'''
global x
x = []
def check(L):
global i
if type(L[i]) != list:
x.append(L[i])
i += 1
return check(aList[i])
else:
return check(L[i])
return check(aList)`
and I keep getting this error
Traceback (most recent call last):
File "<ipython-input-87-ee05c7b1d059>", line 1, in <module>
flatten(l)
File "/Users/ashwin/.spyder-py3/untitled1.py", line 20, in flatten
return check(aList)
File "/Users/ashwin/.spyder-py3/untitled1.py", line 18, in check
return check(L[i])
File "/Users/ashwin/.spyder-py3/untitled1.py", line 16, in check
return check(aList[i])
File "/Users/ashwin/.spyder-py3/untitled1.py", line 13, in check
if type(L[i]) != list:
TypeError: 'int' object is not subscriptable
What is it that I need to change?