0
import random
from IPython.display import clear_output

dictionary = open("words_50000.txt","r")
dict_5000 = dictionary.readlines()
guess = random.choice(dict_5000).lower().strip('\n')
no_of_letters = len(guess)
game_str = ['-']*no_of_letters
only_length=[]

def word_guesser():
    only_length_words()
    print(dict_5000)


def only_length_words():
    for i in range(len(dict_5000)):
        if len(dict_5000[i].strip('\n'))!=no_of_letters:
            dict_5000.pop(i)    

word_guesser()

--------------------------------------------------------------------------- IndexError Traceback (most recent call last) in () 20 dict_5000.pop(i) 21 ---> 22 word_guesser()

in word_guesser() 11 12 def word_guesser(): ---> 13 only_length_words() 14 print(dict_5000) 15

in only_length_words() 17 def only_length_words(): 18 for i in range(len(dict_5000)): ---> 19 if len(dict_5000[i].strip('\n'))!=no_of_letters: 20 dict_5000.pop(i) 21

IndexError: list index out of range

Atul Bhatt
  • 485
  • 1
  • 6
  • 15
  • side note: use `with open` construct to open files otherwise you will always keep failing like now - you forgot to close file :); for question - change this`for i in range(len(dict_5000)):` to `for i in range(len(dict_5000)-1):` – Drako Jun 27 '18 at 07:40
  • 2
    Possible duplicate of [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Mel Jun 27 '18 at 07:47
  • That too doesn't help me out. I edited my code the way you mentioned it. I'm now making the same changes in the code under my question. Please check it out. – Atul Bhatt Jun 27 '18 at 07:50
  • somelist[:] = (x for x in somelist if determine(x)) This worked out for me. Thanks for your help. It was nice to have you. – Atul Bhatt Jun 27 '18 at 07:57

1 Answers1

4

The problem is that you are using pop(), which mutilates the list, but you're also iterating over the list. So, let's say there is an element in the list that you popped out. Now, the length of the mutilated list is shorter then the original but the for loop will still try to iterate till the original length of the list and this is causing the IndexError.

Ankit R Gadiya
  • 449
  • 1
  • 7
  • 14