-1

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

b.ang
  • 1
  • 1
  • 2
    why do you use pandas to display the result, instead of print `filtered_lc` directly? – Lei Yang Feb 24 '22 at 15:39
  • 3
    Removing an item from the list changes what you are iterating over in a way that isn't communicated to the iterator. Effectively, you have changed what is in the current position, but the iterator doesn't know that, and moves on to the *next* position without ever having seen the "new" current value. – chepner Feb 24 '22 at 15:40
  • 1
    (Holding off on an answer because there must be a relevant duplicate.) – chepner Feb 24 '22 at 15:41
  • 2
    `str` is a calss name in Python. Don't use it as a variable name! – Shayan Feb 24 '22 at 15:46

1 Answers1

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)
Hot Shot
  • 115
  • 1
  • 5