sum(int(str(x).count("1")) for x in xrange(1000000)) Or, if you prefer to supply the parameters: def howmany( needle, haystack ): return sum(int(str(z).count(str(needle))) for z in xrange(int(haystack)))