What's the best way to Remove Entries From Lists inside of Lists?

Question:

I want to use one list to remove entries from another list, which in itself isn’t hard with one level. But I’m having problems doing this with lists in lists (multiple levels)

list1 = [['orange', 'apple'], ['stone', 'wood', ['stone', 'stone', 'raven']]]

exclusionList = ["stone"]

The result I want:


>>> [['orange', 'apple'], ['wood', ['raven']]]

The solution should be able to dynamically adjust to the amount of list levels.

Asked By: Sidney

||

Answers:

A recursive approach:

list1 = [['orange', 'apple'], ['stone', 'wood', ['stone', 'stone', 'raven']]]

exclusionList = ["stone"]


def remove(lst, exclusion):
    result = []
    for e in lst:
        if isinstance(e, list):
            result.append(remove(e, exclusion))
        elif e not in exclusion:
            result.append(e)
    return result


res = remove(list1, exclusionList)
print(res)

Output

[['orange', 'apple'], ['wood', ['raven']]]
Answered By: Dani Mesejo

This seems like it would admit a recursive solution. To begin with, here’s what you probably have for normal, "one-level" (flat) lists.

#there's better ways to implement this function specifically
def remove_items(main_list, blacklist):
    for item in blacklist:
        if item in main_list:
            main_list.remove(item)

The solution is to apply this to your list, and each of its elements, recursively.

def remove_items_nested(main_list, blacklist):
    remove_items(main_list, blacklist)
    for sublist in main_list:
        if not isinstance(sublist, list): continue
        remove_items_nested(sublist, blacklist)
Answered By: Xavi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.