How to Convert an Int to a List of Ints in Python


The challenge

Given a non-negative integer, return an array / a list of the individual digits in order.

Examples:

123 => [1,2,3]
1 => [1]
8675309 => [8,6,7,5,3,0,9]

The solution in Python code

Option 1:

def digitize(n):
    return [int(d) for d in str(n)]

Option 2:

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

Option 3:

def digitize(n):
    lst = []
    if n == 0:
        return [0]
    while n:
        n,r = divmod(n,10)
        lst.append(r)
    lst.reverse()
    return lst

Test cases to validate our solution

import test
from solution import digitize

@test.describe("Fixed Tests")
def fixed_tests():
    @test.it('Basic Test Cases')
    def basic_test_cases():
        test.assert_equals(digitize(123), [1,2,3])
        test.assert_equals(digitize(1), [1])
        test.assert_equals(digitize(0), [0])
        test.assert_equals(digitize(1230), [1,2,3, 0])
        test.assert_equals(digitize(8675309), [8,6,7,5,3,0,9])