0

I have an issue with removing consecutive duplicates in a list without removing all duplicates.

Say I have a list,

a = [3,3,3,4,10,11,3,3,5,5,10]

What I want to do is whenever there is a duplicate in a row, that duplicate is changed to a single value. I want this to happen for any number of consecutive duplicates. Thus I want my new a to be,

new_a = [3,4,10,11,3,5,10]

Notice I don't want to remove the other duplicates, like the set function would do, I just want to change consecutive duplicates into one value.

Here is my attempt, which works sometimes but not on all my lists, most likely because I'm not sure how to set up the general rule for my range.

for i in range(0, len(set(a))-1):
    if a[i] == a[i+1]:    
          a.pop(i+1)

Any help would be great, thanks.

5 Answers5

2
This might help
a=[3,3,4,10,11,3,5,5,0,0,10,11,11,10,10,0,0]
i=0
while(i<(len(a)-1)):
        if a[i]==a[i+1]:    
          a.pop(i+1)
        i+=1
print(a)
surendra
  • 31
  • 3
1

You can keep track of last item while iterating the list and append the current item to result only if the it is different from the last seen item.

In terms of code,

def solve(l):
    seen = l[0]
    ans = [l[0]]
    for i in l[1:]:
        if i != seen:
            ans += [i]
            seen = i
    return ans

solve([1, 1, 1, 2, 1])
[1, 2, 1]
solve([3,3,3,4,10,11,3,3,5,5,10])
[3, 4, 10, 11, 3, 5, 10]
Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
1

You could do it like this:

a = [3,3,3,4,10,11,3,3,5,5,10]
b = [a[0]]
for x in a[1:]:
    if x != b[-1]:
        b.append(x)
print(b)

Of course, this creates a new list so you could just replace a with b

DarkKnight
  • 19,739
  • 3
  • 6
  • 22
1
a = [3,3,3,4,10,11,3,3,5,5,10]

new_a = []
for i in range(len(a)):
    if a[i] != a[i-1]:
        new_a.append(a[i])
print(new_a)

[3, 4, 10, 11, 3, 5, 10]

Anmol Parida
  • 672
  • 5
  • 16
0

Does this help you?

mylist = ["a", "b", "a", "c", "c"]
mylist = list(dict.fromkeys(mylist))
CozyCode
  • 484
  • 4
  • 13