Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 4c4d3b1

Browse files
committed
Add usage notes for collections.Counter()
1 parent 1862840 commit 4c4d3b1

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

Doc/library/collections.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,33 @@ counts, but the output will exclude results with counts of zero or less.
258258
>>> c | d # union: max(c[x], d[x])
259259
Counter({'a': 3, 'b': 2})
260260

261+
.. note::
262+
263+
Counters were primarily designed to work with positive integers to represent
264+
running counts; however, care was taken to not unnecessarily preclude use
265+
cases needing other types or negative values. To help with those use cases,
266+
this section documents the minimum range and type restrictions.
267+
268+
* The :class:`Counter` class itself is a dictionary subclass with no
269+
restrictions on its keys and values. The values are intended to be numbers
270+
representing counts, but you *could* store anything in the value field.
271+
272+
* The :meth:`most_common` method requires only that the values be orderable.
273+
274+
* For in-place operations such as ``c[key] += 1``, the value type need only
275+
support addition and subtraction. So fractions, floats, and decimals would
276+
work and negative values are supported. The same is also true for
277+
:meth:`update` and :meth:`subtract` which allow negative and zero values
278+
for both inputs and outputs.
279+
280+
* The multiset methods are designed only for use cases with positive values.
281+
The inputs may be negative or zero, but only outputs with positive values
282+
are created. There are no type restrictions, but the value type needs to
283+
support support addition, subtraction, and comparison.
284+
285+
* The :meth:`elements` method requires integer counts. It ignores zero and
286+
negative counts.
287+
261288
.. seealso::
262289

263290
* `Counter class <http://code.activestate.com/recipes/576611/>`_

0 commit comments

Comments
 (0)