1

I would like to remove the words of each nested list that appear in the garbage list.

List to clean:

main_list = [['CV', 'Bob', 'Jones', '20201027'], ['Resume', 'Andrea', 'Jones'], ['Claire', 'Jonson', 'CV', 'Resume', 'Format', 'Test']]

Desired output (only the names):

 [['Bob', 'Jones'], ['Andrea', 'Jones'], ['Claire', 'Jonson']]

current code:

garbage = ['CV', 'Resume', 'Format', 'Person', 'Test' ]

for nested_list in main_list:
    for word in nested_list:
        if word in garbage or word.isdigit():
            nested_list.remove(word)

print(main_list)

current output:

[['Bob', 'Jones'], ['Andrea', 'Jones'], ['Claire', 'Jonson', 'Resume', 'Test']]

This is only a representation of the actual data I am working with, it is important that the filtering is done based on this garbage list. As you can see, in the current output, the 3rd item is not filtered correctly. Why is this and what can be done ?

0

2 Answers 2

4

this should work:

cleaned = [[word for word in sublist if word not in garbage and not word.isdigit()] for sublist in main_list]
4
  • Thanks. Would you care to explain why .remove() in my loop does not work? I am personally not a fan of list comprehensions in terms of readability.
    – blah
    Mar 2, 2021 at 16:04
  • 3
    Should the or be an and in [word for word in sublist if word not in garbage and not word.isdigit()]? Mar 2, 2021 at 16:04
  • 1
    @RazzleShazl yes! thanks for catching
    – George D.
    Mar 2, 2021 at 16:06
  • 2
    @blah removing things from lists you are iterating over causes problems finding the next item appropriately. See here for example.
    – Tom
    Mar 2, 2021 at 16:08
1

The problem you're having is that you're modifying your list whilst trying to iterate through it, which is messing up the indexing.

As a rule, you should not remove items from a list while you are looping through it. If you really need to, you should loop using an index, and carefully track which index you are on when you remove items. This is prone to mistakes, so a better solution is to just generate a new list using items you want to keep.

There is already another answer that solves your issue.

Not the answer you're looking for? Browse other questions tagged or ask your own question.