Skip to content

Issues with collections.Counter #154746

Description

@brass75

Bug report

Bug description:

I have found 2 issues with collections.Counter:

  1. There is a discrepancy between the documentation on docs.python.org and help(collections.Counter). The former includes 2 additional constructor formats that are not mentioned in the help output:
  • class collections.Counter(**kwargs)
  • class collections.Counter(mapping, /, **kwargs)
    Since the help output only includes class collections.Counter(iterable, /, **kwargs) the implication is that a call to collections.Counter({'a': 1, 'b': 2}) will return collections.Counter({'a': 1, 'b': 1}) while in fact it will return collections.Counter({'b': 2, 'a': 1}). This behavior is documented on docs.python.org (although somewhat ambiguously) but not in the help output.
  1. When initializing a collections.Counter object with a Mapping the collections.Counter object that is returned has the mapping reversed:
>>> Counter({'a': 1, 'b': 2})
Counter({'b': 2, 'a': 1})

Since dicts preserve insertion order this behaviour is counterintuitive. Either the order should be preserved or the reversal should be documented.

CC @nedbat @willingc

CPython versions tested on:

3.14

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsDocumentation in the Doc dirpendingThe issue will be closed if no feedback is provided

    Projects

    Status
    Todo

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions