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.


123 => [1,2,3] 1 => [1] 8675309 => [8,6,7,5,3,0,9]
Code language: Python (python)

The solution in Python code

Option 1:

def digitize(n): return [int(d) for d in str(n)]
Code language: Python (python)

Option 2:

def digitize(n): return list(map(int, str(n)))
Code language: Python (python)

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
Code language: Python (python)

Test cases to validate our solution

import test from solution import digitize @test.describe("Fixed Tests") def fixed_tests():'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])
Code language: Python (python)

Notify of
Inline Feedbacks
View all comments