adding an int to int in a list comprehension fails

76 views Asked by At

in this statement

stop_words_index = [word_index.get(w) + 3 for w in stop_words]

word_index.get(w) is an int, but this statement generates

TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

How to fix this?

1

There are 1 answers

0
Gelineau On

word_index.get(w) is None if w cannot be found in dictionnary word_index.

You should do word_index.get(w, 0) if you want this value to be 0 when w is not found.

Or [word_index.get(w) + 3 for w in stop_words if w in word_index] if you want to skip the not found words.