0

I have a question about recursion.

def f6(lst):
result = []
if type(lst[0]) == list:
    return f6(lst[0])
else:
    result.append(lst[0])

    if lst[1]:
        return f6(lst[1])

    else:
        return result

I want to make one dimensional list from multidimensional list input. For example, when I put ["baa",[4,True,[10, 5],[1,2,['moo']]],['chirp']] ,I want to take ["baa",4,True,10, 5,1,2,'moo','chirp']

But it gives me index out of range error at if lst[1]:

Can't I use lst[1] as True/False condition? I appreciate your help.

cs95
  • 379,657
  • 97
  • 704
  • 746
Won Kim
  • 109
  • 9

1 Answers1

2

You're not taking care of conditions where a list can have an arbitrary number of elements and nested lists in any order. You'll need to initialise a results list, and then run a loop across each element to and check if the element is an instance of list (this is cleaner than type(x) == list) and if it is, make a recursive call, and extend the results list. Otherwise, append that element to results.

def f6(lst):
    result = []
    for i in lst:
        if not isinstance(i, list):
            result.append(i)
        else:
            result.extend(f6(i))

    return result

Calling this with f6(["baa",[4,True,[10, 5],[1,2,['moo']]],['chirp']]) produces:

['baa', 4, True, 10, 5, 1, 2, 'moo', 'chirp']
cs95
  • 379,657
  • 97
  • 704
  • 746