Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading