Divide number into digits and save them in list (array) using python
Question
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.
OTHER TIPS
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))
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]