2

I found a solution for my problem here.
The thing is, my answer was exactly the same, except for (checkio(x)), I had just (x).

So instead of this (working solution):

def checkio(data):

    new_list = []
    for x in data:
        if type(x) == list:
            new_list.extend(checkio(x))
        else:
            new_list.append(x)
    return new_list

I had:

def checkio(data):

new_list = []
for x in data:
    if type(x) == list:
        new_list.extend(x)
    else:
        new_list.append(x)
return new_list

Why doesn't that work?
Why do I need to reference the function itself?
What is checkio(x) exactly?

Community
  • 1
  • 1
NoSplitSherlock
  • 605
  • 4
  • 19

1 Answers1

4

You need to recursively call the checkio function in case you have a nested list that is passed in data, so that the nested list gets flattened too.

For example:

data = ["a", "b", ["c", "d"], [["e", "f"], "g"]]
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • Ah ok! I think I get it. It uses the function again (in a different instance?) to go through x (if it's a list) and if it hits another list it goes through the function again? – NoSplitSherlock Aug 25 '13 at 14:16
  • Just to add why this confused me. It didn't occur to me that I could use the function within the function to loop over nested items if the function would find them. It felt like inception for a second. – NoSplitSherlock Aug 25 '13 at 14:18
  • 2
    @NoSplitSherlock Well, it's almost inception, it's called *recursion* ;) – Thomas Orozco Aug 25 '13 at 14:19