Fastest way to loop through each digit in a number?

Rune Strand rst at _nospam_.drlug.org._nospam_
Sun Sep 5 22:56:54 EDT 2004


Hi,
If I have a lot of integers and want do something with each digit as
integer, what is the fastest way to get there? 

Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345"

(Btw: What is the English term for this process; itemize? tokenize?
digitize?  sequence?)

Some examples:

n = 12345

#1.
s = str(n)
for i in s:
    d = int(i)
    foo(d)

#2.
nl = map(int, str(n)) 
for d in nl:
    foo(d)

#3.
nl = [int(x) for x in str(n)]
for d in nl:
    foo(d)

Of those, I have, a bit surprised, found that #1 is the fastest, and
that #2 using map() is faster than #3 using list comprehension. I also
registered that that repr(n) is about 8% faster than str(n).

Are there faster ways? Is it possible to avoid casting types?

Thanks for all answers!




More information about the Python-list mailing list