How can we count text 'changes' in a list?

How can we count text ‘changes’ in a list?

The list below has 0 ‘changes’. Everything is the same.

['Comcast', 'Comcast', 'Comcast', 'Comcast', 'Comcast', 'Comcast']

The list below has 3 changes. First change is Comcast>Sprint, second change is Sprint>AT&T and third change is AT&T>Comcast.

['Comcast', 'Comcast', 'Sprint', 'AT&T', 'Comcast', 'Comcast']

I Googled this before posting here. Finding unique items seems pretty easy. Finding changes, or switches, seems not so easy.

>Solution :

This is an option using itertools.groupby. This counts the number of "chunks" and subtract it by one (to get the "boundaries").

from itertools import groupby

lst = ['Comcast', 'Comcast', 'Sprint', 'AT&T', 'Comcast', 'Comcast']

output = sum(1 for _ in groupby(lst)) - 1
print(output) # 3

Leave a Reply