-1

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?

quamrana
  • 37,849
  • 12
  • 53
  • 71
Ukiyo
  • 327
  • 1
  • 4
  • 13
  • How is this supposed to work? Why are you using a global for `x`? Why are you using a global for `i`? Why are you calling `check(aList[i])` in one case and `check(L[i])` in another? – khelwood Oct 05 '17 at 14:48
  • It looks like `check()` is recursive, but it can't be since there is no base case where you just return. (Plus globals and recursion don't mix very well). – quamrana Oct 05 '17 at 14:57
  • There are multiple questions on SO about this, did you do a search before? We solve problems on SO, not code reviews. Good example though! :) – Anton vBR Oct 05 '17 at 14:59

1 Answers1

4

You can simplify as follows:

def flatten(a_list):
    x = []
    def check(l):
        # Note: check l, not l[i] because l can be anything in the recursive calls
        if not isinstance(l, list):  
            x.append(l)
        else:
            for sub in l:
                check(sub)
    check(a_list)
    return x

> flatten([1, 2, [3, 4, [[5], 6]]])
[1, 2, 3, 4, 5, 6]

There is no hard access to l[i] because you never no what l is. An integer would raise the error that you have encountered. This also gets rid of the need for global variables.

user2390182
  • 72,016
  • 6
  • 67
  • 89