Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove Entries From Lists in Lists

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading