Split a three-digit integer into three list items of each digit in Python

I am new to Python. I want to make a three-digit integer, for example 634 , and split it so that it becomes a list of three elements, i.e.

digits = [ 6, 3, 4 ]

Any help on this would be greatly appreciated.

+8
python
source share
7 answers

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

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

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

 >>> map(int, str(634)) # Python 2 [6, 3, 4] >>> list(map(int, str(634))) # Python 3 [6, 3, 4] 
+20
source share

Using str() bit lazy. Pretty much slower than using math. Using a while will be even faster

 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 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 
+8
source share

Convert to string, treat string as 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] 
+5
source share

Alternatively, you can do this with a 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) 
+3
source share

Like this:

 Python2> i = 634 Python2> digits = [int(d) for d in list(str(i))] Python2> digits [6, 3, 4] 

This turns the int into a string, splits the characters into a list, and maps the list back to ints (using list comprehension).

+1
source share

To do this without converting to a string (and without cheating with a log to find out how many digits there will be), use divmod repeated calls:

 >>> digits = [] >>> value = 634 >>> while value: value,b = divmod(value,10); digits.insert(0,b) ... >>> digits [6, 3, 4] 
+1
source share

You can use this function to turn any number into a list of decimal digits:

 def todigits(n): return map(int, list(str(n))) 

Or do it the other way around:

 def fromdigits(lst): return int("".join(map(str, lst))) 
0
source share

All Articles