-1

I am beginner. I am writing a python program that removes '!' and '.' from the list. User enters any string. Python converts it into a list and removes ! and . and again prints the altered list. Here is my code :

x = input("Enter a string: ")

y = list(x)

for i in range(len(y) - 1):

    if y[i] == '!' or y[i] == '.':
        y.pop(i)
print("Altered list is: ",y)

Even when I do range(len(y)-1) to range(len(y)) it shows the error:
List index out of range.

martineau
  • 112,593
  • 23
  • 157
  • 280

1 Answers1

0

You are iterating over the list that you are modifying... It cannot end well.

Try this approach instead:

y = [elt for elt in y if elt != "!" or elt != "."]

It will rebuild your list, omitting the undesired elements.

Reblochon Masque
  • 33,202
  • 9
  • 48
  • 71