Split three-digit integer to three-item list of each digit in Python

Using str() is a bit lazy. Quite a lot slower than using math. Using a while loop would be faster still

In [1]: n = 634

In [2]: timeit [int(i) for i in str(n)]
100000 loops, best of 3: 5.3 us per loop

In [3]: timeit map(int, str(n))
100000 loops, best of 3: 5.32 us per loop

In [4]: import math

In [5]: timeit [n / 10 ** i % 10 for i in range(int(math.log(n, 10)), -1, -1)]
100000 loops, best of 3: 3.69 us per loop

If you know it's exactly 3 digits, you can do it much faster

In [6]: timeit [n / 100, n / 10 % 10, n % 10]
1000000 loops, best of 3: 672 ns per loop

Alternatively you can do this with the decimal module:

>>> from decimal import Decimal
>>> Decimal(123).as_tuple()
DecimalTuple(sign=0, digits=(1, 2, 3), exponent=0)
>>> Decimal(123).as_tuple().digits
(1, 2, 3)

...which also works with real numbers...

>>> Decimal(1.1).as_tuple()
DecimalTuple(sign=0, digits=(1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 1, 7, 8, 4, 1, 9, 7, 0, 0, 1, 2, 5, 2, 3, 2, 3, 3, 8, 9, 0, 5, 3, 3, 4, 4, 7, 2, 6, 5, 6, 2, 5), exponent=-51)
>>> Decimal('1.1').as_tuple()
DecimalTuple(sign=0, digits=(1, 1), exponent=-1)

You can convert the number to a string, then iterate over the string and convert each character back to an integer:

>>> [int(char) for char in str(634)]
[6, 3, 4]

Or, as @eph rightfully points out below, use map():

>>> map(int, str(634))        # Python 2
[6, 3, 4]

>>> list(map(int, str(634)))  # Python 3
[6, 3, 4]

Convert to string, treat string as a list and convert back to int:

In [5]: input = 634
In [6]: digits =[int(i) for i in str(input)]
In [7]: print digits
[6, 3, 4]

Tags:

Python