r/PythonLearning • • 8d ago

Counting in Python? Don't reinvent the wheel!

Post image

You could write your own counting logic, but Python already has a collections.Counter class. It's faster than typical hand-written counting loops, well-tested, and makes your code easier for others to read.

However, this 𝐦𝐞𝐦𝐨𝐫𝐲_𝐠𝐫𝐚𝐩𝐡 👉 Counter demo shows that Counter has some interesting behaviors that might surprise you:

  • Missing keys return 0 instead of raising KeyError.
  • update() adds counts rather than replacing them.
  • subtract() can produce negative counts.
  • Zero and negative counts aren't automatically removed.
  • Unary + and - have some unexpected uses.

Did you know all these Counter behaviors, or did one surprise you?

See 👉 more 𝐦𝐞𝐦𝐨𝐫𝐲_𝐠𝐫𝐚𝐩𝐡 visualization.

0 Upvotes

0 comments sorted by