Jam
Jam

Reputation: 31

Python: Putting the contents of a series of nested lists into a single list

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?

Upvotes: 0

Views: 192

Answers (1)

Kevin
Kevin

Reputation: 76194

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:

Upvotes: 3

Related Questions