Following @TomKarzes comment, there are several flaws in your logic:
- you are iterating over the list while modifying it
- you iterate over the items, and try to get their index with
index
which is a nonsense. If you need to iterate over indices just do that.
- even if you did not remove items while iterating over the list,
index
only finds the first occurrence of an item.
One option with a loop could be:
def remove_adjacent(nums):
out = []
prev = None
for num in nums:
if num != prev:
out.append(num)
prev = num
return out
remove_adjacent([1, 2, 3, 3, 4])
# [1, 2, 3, 4]
NB. If you want to update the original list in place, replace return out
by nums[:] = out
.
Another option could be to use itertools.groupby
:
from itertools import groupby
out = [k for k, _ in groupby(nums)]