Search code examples
pythonarrayslistnumbersdigits

Divide number into digits and save them in list (array) using python


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.


Solution

  • 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.