Week 5 exercise on most common 2grams

The piece of code I wrote is:

for i in range(len(words)):
  temp_tuple = (words[i], words[i+1])
  words_2grams.append(temp_tuple)
print(words_2grams)

I get the follwing error

IndexError                                Traceback (most recent call last)
<ipython-input-27-707e8a14bd46> in <module>()
      1 for i in range(len(words)):
----> 2   temp_tuple = (words[i], words[i+1])
      3   words_2grams.append(temp_tuple)
      4 print(words_2grams)

IndexError: list index out of range

Annoyingly when I run the folowing code, it works

for i in range(len(words)):
  print(words[i], words[i+1])

the output I get is what I want:-

There is
is the
the program
program for
for checking

I have narrowed down the problem to this bit words[i+1] . I don’t get why words[i+1] works fine in a print command but throws an index error when I am trying to add it to a tuple.

Would appreciate all help.

Thanks.

The issue is, in the last iteration of for loop, it is accessing i+1th element which is not present.

Hence simply iterate 1 less than the length of words, as below

words_2grams = []
words = "This is a program to test 2-grams".split()
for i in range(len(words)-1):
  temp_tuple = (words[i], words[i+1])
  words_2grams.append(temp_tuple)
print(words_2grams)

Hi Rajeev,

As pointed out by Pandurang, your issue occurs during the final iteration of the for-loop, when the [i+1]th element is trying to be accessed. With regards to the output appearing fine during your print statement, the following code would suggest otherwise.

Screenshot from 2020-03-18 22-38-38

I recommend that you check your code once again.