2

I want to divide number into digits and save them in list (or array) in python. So firstly I should create list like

dig = [0 for i in range(10)]

and then

i = 0
while num > 9:
    dig[i] = num % 10
    i += 1
    num /= 10
dig[i] = num

But I don't really like just creating list for 10 spaces, is it possible to get length of number without repeating loop

i = 0
num2 = num
while num2 > 9:
    num2 /= 10
    i += 1
i += 1

and then repeat first part of code? Or just make as I made in first place? I don't know exact length of number but it won't be very long

So any advices? Maybe you know better way to divide numbers into digits, or maybe something else.

Templar
  • 1,843
  • 7
  • 29
  • 42

3 Answers3

10

Since you're just adding the digits from smallest to greatest in order, just use an empty list:

dig = []
i = 0
while num > 9:
    dig.append(num % 10)
    i += 1
    num /= 10
dig.append(num)

Alternatively, just do

dig = list(int(d) for d in str(num))

Which will turn i.e. 123 into '123' then turn each digit back into a number and put them into a list, resulting in [1, 2, 3].

If you want it in the same order as your version, use

dig = reversed(int(d) for d in str(num))

If you really just want to get the length of a number, it's easiest to do len(str(num)) which turns it into a string then gets the length.

agf
  • 171,228
  • 44
  • 289
  • 238
  • it maybe small difference but anyway, if numbesr very big and you have a lot of them, which method is more optimal, that one with loop, mod, div, or just list(int(d) for d in str(num)? – Templar Aug 19 '11 at 11:51
  • 1
    The division version is 400x faster than the string version. – agf Aug 19 '11 at 12:16
5

Assuming num is a positive integer, the number of digits is equal to int(math.log10(num) + 1).

But better than that is to just use the append method of list -- then you won't have to know the length beforehand.

Even easier (though the list will be in reverse order):

dig = [int(x) for x in str(num)]

or

dig = map(int, str(num))
Lauritz V. Thaulow
  • 49,139
  • 12
  • 73
  • 92
2

Although map is often said to be unpythonic, this task is definitely for it:

>>> d = 123456
>>> map(int, str(d))
[1, 2, 3, 4, 5, 6]
Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75