1

Im writing a program to try to calculate how many times the most repeated word in a list occurs. I keep getting an error that says: index error. Even though when I print the list of my word_list, it shows there are 108 elements. Could someone point me in the right direction as to where my error is?

  length = len(word_list)
  num = 0
  print(length)

    while num <= length:

            ele = word_list[num]

            if ele in wordDict:
                    wordDict[ele] = wordDict[ele] +1
                    repeat = repeat + 1
                    if repeat > highestRepeat:
                            highestRepeat = repeat

            else:
                    wordDict[ele] = 1
                    repeat = 1

            num = num+1
2
  • Where do you define repeat? I think you should use you just if wordDict[ele] > highestRepeat Commented Apr 10, 2016 at 5:53
  • 1
    In while num <= length: change <= to < Commented Apr 10, 2016 at 5:55

2 Answers 2

3

List indexing goes from 0 to length-1.

In your while loop, you've told the num to go from 0 to length. That's why you have an index error.

Simply change num <= length to num < length. That should fix your code for you.


As an aside, there are much better ways to do this particular task. A simple two liner:

from collections import Counter

print(Counter(word_list).most_common(1))

Counter will calculate the frequencies of each element in your list for you, and most_common(1) will return the element with the highest frequency in your list.

Sign up to request clarification or add additional context in comments.

Comments

1

Just to mention that there is a more compact solution to your problem:

word_list =['this' ,'is', 'a', 'test', 'is']

for word in set(word_list):
    print word, ": ", word_list.count(word)

2 Comments

This will print all words and their counts, not the word with maximum count (as the OP asks).
Correct, Counter is a better solution, answers have crossed. Just wanted to point into the direction of avoiding loops by using a standard python approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.