Drop Dublicates, if they are in a row in Python

Question:

I got list like:

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

and I want to drop the element of list, if its get repeated.

Output:
[1,5,4,6,5]

I can only find solution for "normal" Duplicate-Problems.

Asked By: AkademiLegi

||

Answers:

my_list = [1,1,5,4,6,6,5]

# Iterate over the elements of the list
for i in range(len(my_list)):
  # Check if the current element is the same as the previous element
  if i > 0 and my_list[i] == my_list[i-1]:
    # If it is, remove the current element from the list
    my_list.pop(i)

# Print the resulting list
print(my_list)  # [1, 5, 4, 6, 5]
Answered By: Anass Kartit

You can use itertools.groupby and just pull the key for each group.

from itertools import groupby

[k for k, _ in groupby([1,1,5,4,6,6,5])]
# returns:
[1, 5, 4, 6, 5]
Answered By: James

You can iterate over pairs with zip and build a new list

lst = [1, 1, 5, 4, 6, 5, 5]
lst = [x for x, y in zip(lst, lst[1:]) if x != y] + [lst[-1]]
print(lst) # [1, 5, 4, 6, 5]
Answered By: Guy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.