-1

I am trying to delete duplicate elements in a array. There are lots of methods out there but I am trying to come up with my own one and tried the folllowing code.

x=[2,1,3,5,3,5]
for i in range(0,len(x)):
  for j in range(0,len(x)):
      if (x[i]==x[j+1]):
           del x[j+1]
for k in range(0,len(x)):
    print(x[k])


I get the following error at line 4 list index out of range.

Please help me!

Mohinish Teja
  • 55
  • 1
  • 8

1 Answers1

0

There are two errors I can see:

  1. You are using j+1 in your program. When the second for loop reaches the end of the loop, j would equal 5, and then j+1 would equal 6, but x[6] would be out of bounds.
  2. Deleting the element from the array changes the length of the array. For example, your array starts with a length of 6, but then, after one of the elements is deleted, it instead has a length 5. However, the for loop doesn't recognize this, and still goes until i=5 instead of stopping at i=4, and x[5] is out of bounds.
Nobozarb
  • 344
  • 1
  • 12