Python – Consecutive identical elements count


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.

  • This is converted to a set and then to a list, and its length is assigned to a variable.

  • This is the output that is displayed on the console.

Updated on: 14-Sep-2021

830 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements