Atul Bhatt
Atul Bhatt

Reputation: 635

I don't know why I'm getting this error or index out of range. I'm using Python 3.0 in jupyter notebook

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

Upvotes: 0

Views: 143

Answers (1)

Ankit R Gadiya
Ankit R Gadiya

Reputation: 489

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.

Upvotes: 5

Related Questions