0

Edits: Updated 'hi' to 'list'

I am a beginner and I have been working on a project to translate English sentences into pig latin, but I have run into an issue while trying to remove the spaces before punctuation in the sentence. Here is the script I am having trouble with.

import string

list = ['H', 'i', 's', 't', 'a', 'y', ' ', 's', 'i', 'a', 'y', ' ', 'a', 'a', 'y', ' ', 'e', 's', 't', 't', 'a', 'y', ' ', '.', ' ', 'H', 'i', 's', 't', 'a', 'y', ' ', 's', 'i', 'a', 'y', ' ', 'a', 'a', 'y', ' ', 'e', 's', 't', 't', 'a', 'y']

h = 0

for h in range(len(list)):
    if list[h] in string.whitespace:
        if list[h + 1] in string.punctuation:
            list.pop(h)
            h = h + 1
        else:
            h = h + 1
    else:
        h = h + 1

print(list)

When I run it I get the error:

  File " ... ", line 110, in <module>
    if list[h] in string.whitespace:
IndexError: list index out of range

When I print Hi[h] outside of the loop it has no problem with indexing 'h'

Any ideas on where I have made a mistake or what I could change?

If it would be better to see the full file let me know.

1 Answers1

1

You have two lists here: hi and list, where hi is presumably the string that you are trying to convert to Pig Latin.

Note that your loop index is going through the length of hi: for h in range(len(hi)), but in your code, you are using h to index list, for example: if list[h] in string.whitespace. From the error, it would appear that your input string hi is longer than list, so when it encounters a value of h that is more than the length of list, it throws this error.

I think you intended to refer to hi throughout the code (but I may be wrong, it isn't clear from your question), so just replace all instances of list with hi.

Updated to reflect the updated question:

In your code list.pop(h) removes elements from the list, which reduces the size of list. So if it was initially 20 elements long at the time of for h in range(len(list)), the loop still runs till index = 19, but list keeps getting shorter, so at some point, there aren't 20 elements any more.

The common strategy in these situations is to traverse the list backwards. Take a look at the answers here.

Antimony
  • 2,230
  • 3
  • 28
  • 38
  • Yes, thank you. In my original file 'hi' was the name of the list I was using but I changed it to list as an example. I will update my description. However, I am still getting the same error. I cant find a reason for the value of h to be larger than the length of the list 'list'. – Hamish Moocow Nov 20 '17 at 03:05
  • Because you are also popping elements from the list, which reduces the size of `list`. So if it was initially 20 elements long, the loop still runs till index = 19, but `list` keeps getting shorter, so at some point, there aren't 20 elements any more. – Antimony Nov 20 '17 at 03:10