0

Hi its my first week learning python and I am making a hangman game I opened a list of words from a .txt file and then going through the words to remove any words that are shorter than 4 or longer than 7 to make an easy list or words.
When i run the code it removes some of the words but not all of them. I don't understand why and can't seem to figure it out.

Here is the code:

easy_hangman_words = hangman_words("easyhangman.txt")  

for x in easy_hangman_words:  
   print(" {} length {} ".format(x, len(x)))

for word in easy_hangman_words:
    if len(word) < 4 or len(word) > 7:
        print(word)
        easy_hangman_words.remove(word)     

I checked the length of each word before if statement and here is a sample:

represent length 9, Republican length 10, require length 7 , research length 8 , resource length 8 , respond length 7 , response length 8 , responsibility length 14 , rest length 4 , result length 6 , return length 6 , reveal length 6 , rich length 4 , right length 5 , rise length 4 , risk length 4 , road length 4 , rock length 4 , role length 4 , room length 4 , rule length 4 , run length 3 , safe length 4 , same length 4 , save length 4 , say length 3 ,

then printed the words in the if loop and here is what i got

represent

research

response

run

say

it seems to have missed Republican, responsibility, and resource. Any ideas?

KerryLisa
  • 3
  • 1

1 Answers1

2

You're both reading (in the for loop) and modifying (the remove) the list! This can cause python's for loops to get pretty wonky. There are more pythonic ways to do this, but this should fix the traversal problem.

You should try something like this:

remove_words = []
for word in easy_hangman_words:
    if len(word) < 4 or len(word) > 7:
        print(word)
        remove_words.append(word)

for remove in remove_words:
    easy_hangman_words.remove(word)
Jack Thomson
  • 450
  • 4
  • 9
  • 1
    Well explained, but I feel a better solution would be to fill in a brand new array `allowed_words` :) (Which can be done in-place with a short list comprehension -- but I digress.) – Jongware Feb 06 '20 at 21:42
  • That worked! Thank you for your help. I can kind of see how maybe deleting and reading at the same time could cause problems :) – KerryLisa Feb 06 '20 at 23:13