-2

I am trying to delete duplicate elements in the list. The code below says index out of range when the value of i goes to 9. 9 + 1 = 10 is not outside the list and I can print it, but whenever I use del it gives me error. This is the code that doesn't work:

a = [12,12,34,34,56,11,32,32,11,10,10]
g = len(a)
for i in range(0,g-1):
    if a[i] == a[i+1]:
        del a[i]
print a

However the reverse logic which is I having value from 10 - 1 works but i from 0 - 9 doesn't work. This one works the reverse logic.

a = [12,12,34,34,56,11,32,32,11,10,10]
g = len(a)
for i in range(g-1,0,-1):
    if a[i] == a[i-1]:
        del a[i]
print a

Can someone explain why, please?

Celeo
  • 5,583
  • 8
  • 39
  • 41
Sam Thomas
  • 57
  • 1
  • 7
  • 9 may not be out of range when the loop starts, but what about after you delete a few elements? – user2357112 Nov 24 '15 at 19:07
  • well regardless the elements deleted are the same for both , 4 of them get deleted duplicated values that is. The first checks duplicates from starting of list the second from end , what difference does it make? – Sam Thomas Nov 24 '15 at 19:09
  • if it starts from the end, then that means your indexes are getting smaller as your list is getting smaller. if it starts from the start, your indexes are getting larger as your list is getting smaller – R Nar Nov 24 '15 at 19:11
  • Ah got it now thanks :) – Sam Thomas Nov 24 '15 at 19:14

1 Answers1

3

You are deleting elements off the list, so it gets shorter. You should create a new list:

last = None
b = []
for value in a:
    if value != last:
        b.append(value)
    last = value
Daniel
  • 42,087
  • 4
  • 55
  • 81