Using "Counter" in Python 3.2

Question:

I’ve been trying to use the Counter method in Python 3.2 but I’m not sure if I’m using it properly. Any idea why I’m getting the error?

>>> import collections
>>> Counter()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    Counter()
NameError: name 'Counter' is not defined

I can access the Counter if I go collections.Counter(), but not the examples in the documentation.

Asked By: AlphaTested

||

Answers:

You want from collections import Counter. Using import collections only makes the stuff in collections available as collections.something. More on modules and the workings of import in the first few sections of this tutorial chapter.

Answered By: hobbs

Try this its working fine using Counter

import collections
print collections.Counter(['a','b','c','a','b','b'])

Output:

Counter({'b': 3, 'a': 2, 'c': 1})
Answered By: jagadesh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.