The problem arises when you remove items from a list you are iterating over. Iteration works like this: each index in a list is visited once, from beginning to end. When you delete something, the contents of the list are shifted left:
| 1 | 2 | 3 | 4 | 5 | << your list
| 1 | 2 | | 4 | 5 | << 3 is deleted
| 1 | 2 | 4 | 5 | << the list fills in the gap
However, the index of the iterator doesn't know the rest of the list has changed one index to the left, so it advances.
Normally, this is how a list iterates:
| 1 | 2 | 3 | 4 | 5 |
^ < index of iterator
| 1 | 2 | 3 | 4 | 5 |
^ The index advances, all is good.
When you delete terms, though, this is what happens:
| 1 | 2 | 3 | 4 | 5 |
^ index
| 1 | 2 | 4 | 5 |
^ Oops! The iterator skips over the missing 3, and never gets to it.
You can fix this in your by manually iterating through the indices, only advancing if a deletion was not made:
def remove_adjacent(nums):
previous = ''
i = 0;
while i < len(nums):
if nums[i] == previous:
nums.remove(i)
else:
previous = nums[i]
i+=1
return nums
This avoids having to make a soft copy of the list with [:] (although that is another approach)
Hope this helps!