Issue 20068: collections.Counter documentation leaves out interesting usecase (original) (raw)

I think the documentation for collections.Counter can be updated slightly to include an example showing the initialization of a counter object from a list. For example, it explains how to manually iterate through a list and increment the values...

for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: ... cnt[word] += 1

I think it is more useful and powerful to do something like this:

cnt = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])

where the result would be:

Counter({'blue': 3, 'red': 2, 'green': 1})

Just a thought. I'm curious to see what other people think.

The introductory example already shows both ways of using a Counter:

  1. How to tally one at a time:

    cnt = Counter() for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']: cnt[word] += 1

  2. How to count directly from a list:

    words = re.findall(r'\w+', open('hamlet.txt').read().lower()) Counter(words).most_common(10)