[docs] collections.Counter - incorrect usage in documentation

Graeme Stuart ggstuart at gmail.com
Tue Nov 18 18:42:27 CET 2014


Hi,

I think this section in the docs
<https://docs.python.org/2/library/collections.html#counter-objects> shows
incorrect and confusing usage for the Counter class.

>>> # Tally occurrences of words in a list>>> cnt = Counter()>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:...     cnt[word] += 1>>> cntCounter({'blue': 3, 'red': 2, 'green': 1})


The example provided iterates over a list of words and manually calculates
the totals as would be done when using e.g. a defaultdict(int) approach. It
uses no features that the Counter specifically provides.

The point of the Counter class is that it does this work for you. The
correct usage is as follows:

>>> words = ['red', 'blue', 'red', 'green', 'blue', 'blue']
>>> cnt = Counter(words)
>>> cnt
Counter({'blue': 3, 'red': 2, 'green': 1})
>>> cnt.items()
[('blue', 3), ('red', 2), ('green', 1)]

This example could be used to replace the existing one. Perhaps the
existing example could be used to demonstrate how to do the same task
without a Counter for comparison?

Cheers

Graeme
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/docs/attachments/20141118/780141ea/attachment.html>


More information about the docs mailing list