0

The problem is such:

I have a series of lists, always containing two items. Each of these items can be either a string or another list. The goal is to figure out how to make all these items from lists appear in a single resultant_list, and return that resultant_list.

My code so far looks like (where nest is the list to be stripped):

def strip(nest):
    result_list=[]
    for item in nest:
        if type(item) is str:
            result_list.append(item)
        else:
            return result_list + strip(item)

Where am I going wrong here?

Jam
  • 31
  • 7

1 Answers1

3

If you return inside your else block, then the for loop might terminate prematurely and you won't iterate over every element. Wait until the loop ends before returning anything.

def strip(nest):
    result_list=[]
    for item in nest:
        if type(item) is str:
            result_list.append(item)
        else:
            result_list.extend(strip(item))
    return result_list

Also, this probably doesn't cause a bug in your specific case, but: it's generally preferable to use isinstance to test the type of an object instead of is. E.g. if isinstance(item, str): instead of if type(item) is str:

Kevin
  • 74,910
  • 12
  • 133
  • 166
  • 3
    Or in other words: The problem with OP's code is that he calls `strip` recursively on the first non-string element it sees, but never examines the following elements. – timgeb Apr 20 '17 at 16:02