-2

I wrote a code that removes duplication in a string, but the problem is in the condition I have an error: index is out of range! The input is: rooobert and output: robert

n = list(input())
s=[]
for i in range(0,len(n)-1):
    if n[i] == n[i+1]:
     n.remove(n[i])

print(n)
Mohamad Sh
  • 41
  • 5
  • What do you thing happens when you remove elements from the list, while `i` will still come from range based on the original length? – buran Sep 18 '21 at 16:14

2 Answers2

0

You are removing from that same string/list; it starts with length n, and whenever you remove a character the length goes down by 1, hence you'll get out of range.

You can change your code to use a new string for the result:

newList = []
for i in range(0,len(n)-1):
   if n[i] != n[i+1]: # notice the flip of the comparison here
      newList += n[i]
saedx1
  • 984
  • 6
  • 20
0

You can do it by tracking the previous element and then creating a newlist. Deleting from the list that you are iterating is generally a bad idea.

n = list("rooobert")
s=[]
prev = None
for i in range(0,len(n)):
    if n[i] != prev:
     s.append(n[i])
    prev = n[i]
print(s)

OUTPUT

['r', 'o', 'b', 'e', 'r', 't']
Albin Paul
  • 3,330
  • 2
  • 14
  • 30