Reputation: 23
I'm getting an error "List out of range. Though I found the other way round for this error, but can I know how can I solve this error.
Upvotes: 0
Views: 94
Reputation: 375
Try setting the range to be:
len(words) - 1
So the for
loop will be:
for i in range(len(words)-1):
len(words)
will return the literal number count of the length, but when iterating over the range, the range begins at 0, so you want your range to be len(words) - 1
Upvotes: 0
Reputation: 1856
Problem is not with your for loop
as everyone suggested. Problem is with synset
for the word 'the' as synset entry for 'the' does not exist. You can replace your code with the below code:
for i in range(len(words)):
synset = wordnet.synsets(words[i])
if synset:
print ("Synonym of the word "+words[i]+" in the list is: "+synset[0].lemmas()[0].name())
else:
print ("Synonym of the word "+words[i]+" not found in the list")
Output:
Synonym of the word After in the list is: after
Synonym of the word getting in the list is: acquiring
Synonym of the word the not found in the list
Synonym of the word proper in the list is: proper
Synonym of the word co-ordinates in the list is: coordinate
Hope the above code helps you out!
Upvotes: 2
Reputation: 91
len
in this case is 5, so range is creating a range that goes from 0 up to 5, whereas your list indexes go from 0 to 4.
You could rewrite that line as:
for i in range(len(words)-1):
Otherwise, if you only need the word and not an index you could just write
for word in words:
Finally, if you need both the word and an index you could use enumerate()
for i, word in enumerate(words, start=0):
Upvotes: 2
Reputation: 77
You don't need to use the len() function or the range() function. You can just use:
for i in words:
synset = wordnet.synsets(i)
print(i + synset)
Upvotes: 1
Reputation: 99
len()
The function gives the output as 5 in this case, because the counter starts from 1 instead of 0. So if you want to loop through the list, use:
for i in range(len(words) - 1):
This will count up to the last element instead of going over and giving an error.
Upvotes: 0