Jeremy Meyer Jeremy Meyer - 2 months ago 15
Python Question

Iterating over list slice in Python not working as expected

I've got this Python 3.5 code:

8 class MarkovDict:
13 def add(self, corpus=None):
14 if corpus == None:
15 return
16 prev_word = corpus[0]
17 for word in corpus[1:]:
18 self.dict[prev_word].append(word)

Should take
which is a list of strings.
Giving this error:

Traceback (most recent call last):
File "", line 23, in <module>
File "", line 17, in main
bot = MarkovBot(full_markov_dict)
File "/Users/jeremy/code/markov/", line 5, in __init__
self.forward_dict = markov_dict.cloned()
File "/Users/jeremy/code/markov/", line 27, in cloned
return MarkovDict(copy.deepcopy(self.dict))
File "/Users/jeremy/code/markov/", line 11, in __init__
File "/Users/jeremy/code/markov/", line 17, in add
for word in corpus[1:]:
TypeError: unhashable type: 'slice'

What am I missing?


Your corpus object is a dictionary rather than a list. When you try to index a dictionary with a slice, it knows that slices are an unhashable type that can never be added to a dictionary, so it tells you that right away.