TypeError in Python, how do I resolve it? | SoloLearn: Learn to code for FREE!


TypeError in Python, how do I resolve it?

# I'm trying to make a Zipf's Law observation using a dictionary that stores every word, and a counter for it. I will later sort this from ascending to descending to prove Zipf's Law in a particular text. I'm taking most of this code from Automate the Boring Stuff with Python, where the same action is performed, but using letters instead. message = 'the of' words = message.split() wordsRanking = {} for i in words: wordsRanking.setdefault(words[i], 0) wordsRanking[i] += 1 print(wordsRanking) ------------------------------------------- This code gives me the following error: TypeError: list indices must be integers or slices, not str How do I resolve this? I would be really grateful.

11/16/2019 11:26:09 AM

Aaryan Pandey

2 Answers

New Answer


I think there is an easier solution: simply change ...setdefault(words[i], 0) to ...setdefault(i, 0). In your example where message = "the of", for i in words means that the code is iterated twice, once with i = "the" and once with i = "of". words[i] is causing an error because you are trying to call an index of the list 'words' with a string, which you don't need to do anyway.


when you use, for i in words. i becomes a string not an integer. an index has to be Integer. use : for i in range() instead. define the range inside the parentheses.