Reputation: 13
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.
Upvotes: 1
Views: 380
Reputation: 11814
You could keep track of the last value you saw and only append to a new list if it's the same as the current value:
numbers = [1,1,2,4,5,6,5]
duplicates = []
previous = None
for n in numbers:
if n == previous:
duplicates.append(n)
previous = n
You could also use zip
and slice the list to view the previous items as you loop:
duplicates = []
for previous, item in zip(numbers, numbers[1:]):
if previous == item:
duplicates.append(item)
An equivalent list comprehension:
duplicates = [
item
for previous, item in zip(numbers, numbers[1:]
if previous == item
]
Note that these both append duplicates more than once if they appear multiple times in a row.
Upvotes: 1
Reputation: 11476
if consecutive repeated values must be found, I'd use itertools.groupby
:
items = [1,1,2,4,5,6,5]
[g for g, l in itertools.groupby(items) if len(list(l)) > 1]
Other way could be by zipping your list and comparing adjacent values:
[e1 for e1, e2 in zip(items, items[1:]) if e1 == e2]
Upvotes: 2
Reputation: 91555
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]
Upvotes: 0