Checking for Consecutive Duplicates in a Python List

I came across this problem statement today and thought of sharing it — because the mistake it exposes is more common than you'd think. Task: Check if an array has consecutive duplicate elements. My first instinct? def duplicate(ls, n): if len(ls) == len(set(ls)): return False return True Looks clean. But it's wrong. This returns True for [1, 2, 1] — even though there are NO consecutive duplicates. It just checks if any value repeats anywhere in the list. The correct approach is to compare neighbouring indices: for i in range(len(ls) - 1): if ls[i] == ls[i + 1]: return True return False Same problem. Completely different logic. That small distinction consecutive vs. anywhere: changed everything. This is what I enjoy about Python. It doesn't just test your syntax. It tests how clearly you understand the problem before you write a single line. #Python #DataAnalyst #CodingTips #DataAnalytics

  • graphical user interface, text, website

To view or add a comment, sign in

Explore content categories