Last modified: Mar 06, 2025 By Alexander Williams

Fix Python NameError: Name 'Counter' Not Defined

Encountering a NameError in Python can be frustrating. One common error is NameError: Name 'Counter' Not Defined. This article explains why this happens and how to fix it.

What Causes the NameError: Name 'Counter' Not Defined?

The error occurs when Python cannot find the Counter class in your code. This usually happens because the Counter class is not imported from the collections module.

For example, if you try to use Counter without importing it, Python will raise this error:


# Example of incorrect usage
my_list = [1, 2, 2, 3, 3, 3]
count = Counter(my_list)


NameError: name 'Counter' is not defined

How to Fix the NameError: Name 'Counter' Not Defined

To fix this error, you need to import the Counter class from the collections module. Here’s how you can do it:


# Correct usage with import
from collections import Counter

my_list = [1, 2, 2, 3, 3, 3]
count = Counter(my_list)
print(count)


Counter({3: 3, 2: 2, 1: 1})

By importing Counter, Python recognizes the class and the error is resolved.

Common Mistakes to Avoid

One common mistake is forgetting to import Counter from the collections module. Another mistake is misspelling the module name. For example, writing from collection import Counter will also raise an error.

Always ensure you import the correct module and class. If you encounter similar errors with other classes like defaultdict or Thread, check out our guides on fixing NameError: Name 'defaultdict' Not Defined and fixing NameError: Name 'Thread' Not Defined.

Conclusion

The NameError: Name 'Counter' Not Defined is a common issue in Python. It occurs when the Counter class is not imported correctly. By importing Counter from the collections module, you can easily resolve this error.

If you face similar errors with other modules like datetime or subprocess, refer to our guides on fixing NameError: Name 'datetime' Not Defined and fixing NameError: Name 'subprocess' Not Defined.

Always double-check your imports and ensure you are using the correct module names. Happy coding!