Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Index out of range after removing item from list

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading