Python find consecutive repeated values

I want to delete the consecutive duplicate values from the array and count unique consecutive values. But I am not getting expected result. Please check and help. Current Output: [aa, bb, aa, cc, cc, dd, ee, cc] [1, 1, 1, 2, 2, 2, 1, 1] Expected Output: [aa, bb, aa, cc, dd, ee, cc] [1, 1, 1, 4, 2, 1, 1] https://code.sololearn.com/W69Q4IqextAQ/?ref=app

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

In this article, we will discuss 3 different ways of removing consecutive duplicate elements from a python list. This is what we want to achieve.

input - [1, 2, 4, 7, 3, 7, 8, 4, 4, 9]
output - [1, 2, 4, 7, 3, 7, 8, 4, 9]

So we are not removing all duplicated elements. We are only eliminating consecutive duplicate elements.

Let’s check out the 3 different ways.

Method 1 - For loops will never go out of fashion

x = [1,2,4,7,3,7,8,4,4,9]

previous_value = None
new_lst = []

for elem in x:
   if elem != previous_value:
       new_lst.append(elem)
       previous_value = elem

print(new_lst)
>>> [1, 2, 4, 7, 3, 7, 8, 4, 9]

Method 2 - Let’s be more Pythonic! Use Enumerate

Here is a one-liner solution to the problem.

x = [1,2,4,7,3,7,8,4,4,9]

print([v for i, v in enumerate(x) if i == 0 or v != x[i-1]])
>>> [1, 2, 4, 7, 3, 7, 8, 4, 9]

Tell me that wasn’t pretty !!

Method 3 - It’s Python! There must be a library

Here is the 3rd way using the itertools library.

from itertools import groupby

x = [1,2,4,7,3,7,8,4,4,9]
print([i[0] for i in groupby(x)])
>>> [1, 2, 4, 7, 3, 7, 8, 4, 9]

Now the question is, which one of the above methods is the fastest?

Using the time and matplotlib library, I plotted the time taken for each of those methods.

Python find consecutive repeated values

You can see that the 3rd approach (using the itertools library) is the fastest of all the 3 ways discussed in this article.

Hope you enjoyed this article. Let me know if you have a better way of doing this, through the comments.

When it is required to get the count of consecutive identical elements in a list, an iteration, the ‘append’ method, and the ‘set’ method are used.

Example

Below is a demonstration of the same

my_list = [24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100]

print("The list is :")
print(my_list)

my_result = []
for index in range(0, len(my_list) - 1):

   if my_list[index] == my_list[index + 1]:
      my_result.append(my_list[index])

my_result = len(list(set(my_result)))

print("The result is :")
print(my_result)

Output

The list is :
[24, 24, 24, 15, 15, 64, 64, 71, 13, 95, 100]
The result is :
3

Explanation

  • A list is defined and is displayed on the console.

  • An empty list is defined.

  • The list is iterated over and if the element in the zeroth index and element in the first index are equivalent, the zeroth element is appended to the empty list.

    Write a Python program to count the frequency of consecutive duplicate elements in a given list of numbers.

    Sample Solution:

    Python Code:

    def count_dups(nums):
        element = []
        freque = []
        if not nums:
            return element
        running_count = 1
        for i in range(len(nums)-1):
            if nums[i] == nums[i+1]:
                running_count += 1
            else:
                freque.append(running_count)
                element.append(nums[i])
                running_count = 1
        freque.append(running_count)
        element.append(nums[i+1])
        return element,freque
    
    
    nums = [1,2,2,2,4,4,4,5,5,5,5]
    print("Original lists:")
    print(nums)
    
    print("\nConsecutive duplicate elements and their frequency:")
    print(count_dups(nums))
    
    

    Sample Output:

    Original lists:
    [1, 2, 2, 2, 4, 4, 4, 5, 5, 5, 5]
    
    Consecutive duplicate elements and their frequency:
    ([1, 2, 4, 5], [1, 3, 3, 4])
    

    Flowchart:

    Python find consecutive repeated values

    Visualize Python code execution:

    The following tool visualize what the computer is doing step-by-step as it executes the said program:

    How do you check for the same consecutive numbers in Python?

    Check if array elements are consecutive in Python.
    if nums[i] < 0, then. j:= -nums[i] - min_val..
    otherwise, j := nums[i] - min_val..
    if nums[j] > 0, then. nums[j] := -nums[j].
    otherwise, return False..

    How do you find consecutive sequences in Python?

    Approach :.
    Create a list..
    Create a loop for range size – 2..
    Check if the element is equal to the next element..
    Again check if the next element is equal to the next element..
    If both conditions are satisfied then print the element..

    How do you find duplicate consecutive elements in a list Python?

    Method #1 : Using loop + set() In this, we iterate and check for the next element, if equal to current, we add in result list, then it is converted to set to get distinct elements.

    How do I get rid of consecutive duplicates in Python?

    Remove Consecutive Duplicates in Python.
    seen := first character of s..
    ans := first character of s..
    for each character i from index 1 to end of s, do. if i is not same as seen, then. ans := ans + i. seen := i..
    return ans..