Bill Maca Bill Maca - 1 month ago 9
Python Question

How do I only detect back to back duplicate elements from a list?

I am trying to detect back to back duplicates from a list. I have tried different duplicate detections, but I have not been able to crawl through the list and detect back to back duplicates.

[1,1,2,4,5,6,5]


only
1
should should be found,
5
should not.

Answer

To find adjacent duplicates you can iterate through your list of items and compare the current one to the next.

items = [1, 1, 2, 4, 5, 6, 5]

for i, item in enumerate(items):
    # don't compare last item to avoid going out of range
    if i < len(items) - 1:
         if item == items[i + 1]:
             print 'duplicate found', item, items[i + 1]

This could be further optimized by removing the last item from the loop. This avoids the need to do an if check to make sure we're not on the last item.

items = [1, 1, 2, 4, 5, 6, 5]

for i, item in enumerate(items[:-1]):
    if item == items[i + 1]:
         print 'duplicate found', item, items[i + 1]