frazman
frazman

Reputation: 33223

Remove duplicate consecutive tuples from list?

Say, I have a list like below:

[(2, 1), (1, 0), (1, 0), (1,0), (2,1), (2, 1)]

I want to remove duplicate consecutive tuples. So in above example, it should return:

[(2, 1), (1, 0), (2, 1)]

Upvotes: 1

Views: 90

Answers (3)

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

a=[(2, 1), (1, 0), (1, 0), (1,0), (2,1), (2, 1)]
a=[elem for count,elem in enumerate(a) if elem!=a[count-1] or count==0]

How about this list comprehension

Upvotes: 1

Tristan
Tristan

Reputation: 1576

You can use itertools.groupby:

from itertools import groupby

x = [(2, 1), (1, 0), (1, 0), (1, 0), (2, 1), (2, 1)]
x_grouped = [i for i, j in groupby(x)]
# [(2, 1), (1, 0), (2, 1)]

Upvotes: 10

Martijn Pieters
Martijn Pieters

Reputation: 1121486

You can use a generator that only yields elements that are not equal to the preceding one:

def filter_consecutive_duplicates(it):
    prev = object()  # sentinel object, won't be equal to anything else
    for elem in it:
        if elem != prev:
            yield elem
        prev = elem

Demo:

>>> list(filter_consecutive_duplicates([(2, 1), (1, 0), (1, 0),(1,0),(2,1), (2, 1)]))
[(2, 1), (1, 0), (2, 1)]

Upvotes: 6

Related Questions