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.
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]
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]
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]
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.
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]
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]
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]