I have an array of numbers and want to print out how many of each number there are in the array. My method works but I was wondering what a more efficient way of doing this would be. I figure a loop would work but I haven't figured out how to do it with this:

s='1234444432187667890000568984'
print 'I found %i:' % s.count('0'),0
print 'I found %i:' % s.count('1'),1
print 'I found %i:' % s.count('2'),2
print 'I found %i:' % s.count('3'),3
print 'I found %i:' % s.count('4'),4
print 'I found %i:' % s.count('5'),5
print 'I found %i:' % s.count('6'),6
print 'I found %i:' % s.count('7'),7
print 'I found %i:' % s.count('8'),8
print 'I found %i:' % s.count('9'),9

I did find this snippet which is fast in counting but doesn't print out like I want it to:

s='1234444432187667890000568984'
ans=dict((i,s.count(i)) for i in set(s))
print ans

Dani AI

Generated

A compact, idiomatic approach is to use collections.Counter so the input is scanned once instead of once per digit. gave a nice one-liner; for larger inputs or many distinct items a single-pass counter is clearer and faster in practice.

Example (replace the sample with your data):

from collections import Counter

s = '1122334444'   # your string or an iterable of digits
counts = Counter(s)

for d in map(str, range(10)):
    print("Digit {}: {} occurrences".format(d, counts[d]))

Notes and tips:

  • Counter does a single pass and returns 0 for missing keys, so iterating 0–9 always prints every digit even if absent.
  • If your data is a list of integers (not a string), pass that list directly to Counter; it works with any hashable items.
  • For tiny strings the difference vs repeated calls to str.count is negligible because count is C-optimized. For long inputs or many unique items, Counter avoids repeated scans and is usually faster.
  • For streaming data or very large inputs, update a Counter incrementally (counts.update(chunk)) to avoid keeping everything in memory.

See the official docs for details: collections.Counter.

Recommended Answers

All 2 Replies

s='1234444432187667890000568984'
print("\n".join(("I found %d: %d" % (s.count(str(i)), i)) for i in range(10)))
commented: Thanks! +1

Wow :) very impressive and exactly what I was looking for. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.