Home > front end >  Index out of range after removing item from list
Index out of range after removing item from list

Time:03-08

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!

CodePudding user response:

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]

CodePudding user response:

This should work, just using a conditional to evaluate if the value is present in wordle to reassign on list

wordle = [x if x in wordle for x in in_word]
  • Related