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

0 min read 104 words

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])
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags