I am making a wordle word finder by taking all possible wordle answers and removing those who don’t fit the word criteria. Currently, I am going through the list of the words and removing those that do not have all user-specified letters. However, when running the program with both a test set and the real set, I get an IndexError: list index out of range on the if statement in the body of the second for loop.
My code:
data = text_file.read()
text_file.close()
def convert(string):
return list(string.split(" "))
wordle = convert(data)
data = input("Enter known letters:\n")
in_word = convert(data)
for i in range(len(wordle)):
for x in range(len(in_word)):
if in_word[x] not in wordle[i]:
wordle.remove(wordle[i])
break
Thanks in advance!
>Solution :
It’s never recommended to edit an object while you’re iterating over it. What is happening is that you’re shortening your list while keeping the for loop the same (so at the end your list could be 3 elements long but your for loop will still count to the original length of 5 – or whatever). I would keep a separate list and just put a condition in your if statement:
skip_list = []
for i in range(len(wordle)):
for x in range(len(in_word)):
if in_word[x] not in wordle[i]:
skip_list.append(wordle[i])
break
wordle = [i for i in wordle if i not in skip_list]