'Nested loops skipping over items in list [duplicate]

The objective I had was to remove all words in a list that contained letters from user input

import pandas as pd

filtered = ['d','dd','ddd','dddd','ddddd','dddddd']
filtered_lc = [x.lower() for x in filtered]

str = input("Input wrong letters (enter blank to skip): ")

for word in filtered_lc:
    for letter in str:
        if letter in word and word in filtered_lc:
            filtered_lc.remove(word)


df = pd.DataFrame(filtered_lc)
print("-----------------------\n", df)

Desired output should be nothing

Output I got:

-----------------------
         0
0      dd
1    dddd
2  dddddd

Could anyone explain why it is only processing for the 1st, 3rd and 5th word in the list please? Thank you



Solution 1:[1]

First of all rename the variable str to something else as it is already type in python.

Also, you are removing from the list you are itterating which can also cause problems.

Try:

import pandas as pd

filtered = ['d','dd','ddd','dddd','ddddd','dddddd']
filtered_lc = [x.lower() for x in filtered]

filtered_lc_cpy = filtered_lc.copy()

_str = input("Input wrong letters (enter blank to skip): ")

for word in filtered_lc_cpy:
    for letter in _str:
        if letter in word and word in filtered_lc:
            filtered_lc.remove(word)


df = pd.DataFrame(filtered_lc)
print("-----------------------\n", df)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1