0

I am trying to creating a function that takes in a list of nested lists which in turn may have nested lists inside them. While it doesn't make sense to me why i should have to do such a thing my lab instructor insists its very useful in future project and in life as whole. here is my attempt to create the double recursive function that accomplishes such a functionality. I would appreciate it if you could point out whats it I am doing wrong and how to solve it.

def flatten_list(list_arg):
    if not list_arg:
        return []
    elif isinstance(list_arg[0],list):
        return [list_arg[0]]        +       flatten_list(list_arg[1:])
    else:
        return [list_arg[0]]        +       flatten_list(list_arg[1:])
print(flatten_list([1,2,[3,[4,[5,6]]]]))

Here is the output:

[1,2,[3,[4,[5,6]]]] which basically means that the function doesn't do a thing and it just consumes some stack memory for a while and terminates with the same input. Oh before I forget this is functional programming so i am not allowed to change variables, produce side effects, or use loops in my function. it should be purely recursive with no variable change etc just like how a regular mathematical function works.

Reddevil
  • 125
  • 3
  • 12
  • Why are you putting `list[0]` back inside a list if it is itself a list? You'll also have to flatten `list[0]` itself in that case. – Martijn Pieters Oct 01 '16 at 13:16
  • @MartijnPieters because i want to return a list as a result not a sum, and by the way, since you marked my question as duplicate, id appropriate it if you refer me to the question that you think is identical to mine, or do you think that its fun to shut down others questions? judging by the number if points you have you should have figured out that you cant concatenate list type with other types than list. so you are not better than me after all, you just are lucky to have more points than me – Reddevil Oct 01 '16 at 13:20
  • What does my reputation have to do with anything here? Your question is a duplicate as the other question solves the exact same problem. – Martijn Pieters Oct 01 '16 at 13:28
  • @Reddevil The linked question is on the top of your question, right after "This question already has an answer here". – The SE I loved is dead Oct 08 '16 at 22:53

0 Answers0