given a list with no unique values, how to return the same list but with consecutive…
- User
given a list with no unique values, how to return the same list but with consecutive duplicated values removed keeping the first entry?
Assistant
Removing Consecutive Duplicates from a List
You can use a simple list comprehension with an
ifcondition to achieve this. Here is a Python solution:def remove_consecutive_duplicates(input_list): """ Removes consecutive duplicates from a list, keeping the first entry. Args: input_list (list): The input list with potential consecutive duplicates. Returns: list: The input list with consecutive duplicates removed. """ return [x for i, x in enumerate(input_list) if i == 0 or x != input_list[i - 1]] # Example usage: input_list = [1, 1, 2, 2, 2, 3, 4, 4, 5, 6, 6] print(remove_consecutive_duplicates(input_list)) # Output: [1, 2, 3, 4, 5, 6]Alternatively, you can use the
itertools.groupbyfunction:import itertools def remove_consecutive_duplicates(input_list): """ Removes consecutive duplicates from a list, keeping the first entry. Args: input_list (list): The input list with potential consecutive duplicates. Returns: list: The input list with consecutive duplicates removed. """ return [k for k, _ in itertools.groupby(input_list)] # Example usage: input_list = [1, 1, 2, 2, 2, 3, 4, 4, 5, 6, 6] print(remove_consecutive_duplicates(input_list)) # Output: [1, 2, 3, 4, 5, 6]Both solutions have a time complexity of O(n), where n is the length of the input list.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.