Given a Python list, I want to remove consecutive 'duplicates'. The duplicate value however is a attribute of the list item (In this example, the tuple
's first element).
Input:
[(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c'), (3, 'd'), (2, 'e')]
Desired Output:
[(1, 'a'), (2, 'b'), (3, 'd'), (2, 'e')]
Cannot use set
or dict
, because order is important.
Cannot use list comprehension [x for x in somelist if not determine(x)]
, because the check depends on predecessor.
What I want is something like:
mylist = [...]
for i in range(len(mylist)):
if mylist[i-1].attr == mylist[i].attr:
mylist.remove(i)
What is the preferred way to solve this in Python?