garyrobinson.net - Gary Robinson's Rants

Description: Python, Coding, Politics

politics (3999) python (3834) coding (2019)

Example domain paragraphs

The simplest way is to use Counter from the collections standard library:

dict(Counter([2,1,1,3,4,4,4,4,4,5,5,2,2,2])) [Hat tip to reader qsantos.]

I like the itertools and more-itertools [1] libraries because they contain many quick solutions for working with iterables. itertools is part of the Python standard library; more-itertools isn't, but it's good to look both of them over to know what's available there. For example, the task of counting values can be done using the run_length() function in more-itertools [1], although that method is a little more verbose than the one using Counter :

Links to garyrobinson.net (1)