r/learndatascience • • 26d ago

Resources Counting in Python? Don't reinvent the wheel!

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.

4 Upvotes

2 comments sorted by

1

u/Deltarayedge7 26d ago

What is that thing in the left

1

u/Sea-Ad7805 26d ago edited 26d ago

It shows what's currently in memory. A visualization of the program state that gets changed by executing each line of the program. Try this exercise for a better understanding of how it can help you with understanding Python.